Cannot read property 'id' of null - JS error - javascript

I have the following html code:
<!DOCTYPE html>
<html>
<head>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
</body>
</html>
Yet in the console, I'm receiving an error when it reaches line 9 when it says "type of null does not exist", but clearly the id of the div must exist because I had it declared as an id in the body. How is this possible?

Your html elements aren't loaded when the script is loaded and so don't exist at the time the javascript is executed. Changing the order of your code will solve the problem:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</body>
</html>

Your JS code is probably running before your HTML has fully rendered. To avoid this, don't run your code until the 'DOMContentLoaded' event has fired.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
// your code here
});
</script>

Please load javascript after the whole html body won't get any error

Related

How to display a string javascript in HTML

In my HTML file I have a div with id="list".
Now I want to display a string from my javascript in my html. page. but nothning
happen. In my html file, i've imported the srcipt file. Here's how it looks in my script file:
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
Whenever you're targeting DOM elements (i.e you want to use document.getElementById("my-element") or similar) you need to first check if the document has loaded.
You can do this in either of the following ways:
window.onload = function(){
//Now that the window has loaded we can target DOM elements here
}
OR
document.addEventListener('DOMContentLoaded', function () {
//Now that the contents of the DOM have loaded we can target DOM elements here
});
So a full example (putting your script code in an external file i.e list.js) would look like this:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8">
<title>My list website</title>
<script src="list.js"></script>
</head>
<body>
<div id="list"></div>
</body>
</html>
list.js
window.onload = function(){
//We use window.onload to check the window has loaded so we can target DOM elements
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
}
place your code in this and it will work
window.onload = function() {}
You need to put the JavaScript code after your dom and also wrapped with Script tag.
Example: This will work since we rendered the HTML first and then executed the js into it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This Will WorK</title>
</head>
<body>
<div id="list" ></div>
<script>
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
</script>
</body>
</html>
But this will NOT work since the JavaScript is being executed before dom rendered. Also this will probably throw an error Cannot set property 'innerHTML' of null" because getElementById will not be able to find the associated dom.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This Will Not WorK</title>
</head>
<body>
<script>
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
</script>
<div id="list" ></div>
</body>
</html>
Here is a succinct way to do it with template strings. Just wrap everything in a function you assign to window.onload:
<script>
window.onload = () => {
const namesArray = ['lars', 'bo', 'ib', 'peter', 'jan', 'frederik'];
const list = `<ul>${namesArray.map(name => `<li>${name}</li>`).join('')}</ul>`;
document.getElementById('list').innerHTML = list;
};
</script>
<div id="list"></div>

How to change an image using an onclick button

I cannot get my images to change when I click each button name. Anyone know what the issue is with my code?
It's not letting me put my code in the description.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hmwk02</title>
</head>
<body>
<h1>Octocats</h1>
<img id="octocats" src= "https://octodex.github.com/images/original.png" alt="octocat" width="150"/>
<div id="buttons"></div>
<script>
let names= ["Castello", "Grinchtocat", "Mummytocat", "Adventure-Cat"];
let urls= ["https://octodex.github.com/images/catstello.png",
"https://octodex.github.com/images/grinchtocat.gif",
"https://octodex.github.com/images/mummytocat.gif",
"https://octodex.github.com/images/adventure-cat.png"];
let lines = "";
for(let i = 0; i< names.length; i++){
lines += '<button onlick="showPicture(' + i +')">' + names[i] + '</button><br/>'
}
document.getElementById("buttons").innerHTML = lines;
console.log(lines);
</script>
<script src="octocats.js"></script>
</body>
function showPicture(i) {
document.getElementById("octocat").src = urls[i];
console.log(i);
}
Your code is fine other than syntax errors, you misspelled onclick in your button tag and you misspelled the ID for the picture--it should be document.getElementById("octocats") not document.getElementById("octocat")
corrected code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hmwk02</title>
</head>
<body>
<h1>Octocats</h1>
<img id="octocats" src= "https://octodex.github.com/images/original.png" alt="octocat" width="150"/>
<div id="buttons"></div>
<script>
let names= ["Castello", "Grinchtocat", "Mummytocat", "Adventure-Cat"];
let urls= ["https://octodex.github.com/images/catstello.png",
"https://octodex.github.com/images/grinchtocat.gif",
"https://octodex.github.com/images/mummytocat.gif",
"https://octodex.github.com/images/adventure-cat.png"];
let lines = "";
for(let i = 0; i< names.length; i++){
lines += '<button onclick="showPicture(' + i +')">' + names[i] + '</button><br/>'
}
document.getElementById("buttons").innerHTML = lines;
console.log(lines);
</script>
<script>
function showPicture(i) {
document.getElementById("octocats").src = urls[i];
console.log(i);
}</script>
</body>
working codepen: https://codepen.io/anon/pen/YBYxgr
An alternative to using the for loop would be to map() the names array and simply use createElement() method to create a new <button> element with a click listener for each item in your names array (you should avoid using inline on* handlers (onclick, oninput, etc) and use IDs and event listeners instead).
Check and run the following Code Snippet for a practical example of what I have described above:
let names= ["Castello", "Grinchtocat", "Mummytocat", "Adventure-Cat"];
let urls= ["https://octodex.github.com/images/catstello.png", "https://octodex.github.com/images/grinchtocat.gif", "https://octodex.github.com/images/mummytocat.gif", "https://octodex.github.com/images/adventure-cat.png"];
names.map((e, i) => { // add function to each element in "names" array
let name = document.createElement("button"); // create <button> element for each item in "names" array
name.id = i; // assign respective index as id of each element
name.textContent = e; // assign item string as button text content
name.addEventListener("click", () => document.getElementById("octocats").src = urls[i]); // add click listener to each <button> that changes image src on click
document.getElementById("buttons").appendChild(name); // append the <button> elements to your `#buttons` div.
});
<h1>Octocats</h1>
<img id="octocats" src= "https://octodex.github.com/images/original.png" alt="octocat" width="150"/>
<div id="buttons"></div>

How to display string length in javascript

I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari

Javascript/HTML Image Change

My task for my Javascript class is to create a script for this page that changes the image every 3 seconds. I think my code is correct, however Firebug tells me "document.getElementByID is not a function." Can someone show me what I am doing incorrectly?
This is my JS script.
<script type="text/javascript">
var i = 0
var lightArray = ["pumpkinOff.gif", "pumpkinOn.gif"]
var currentLight = document.getElementByID('light')
// ChangeLight Method Prototype
function changeLight() {
currentLight.src = lightArray[i++];
if (i == lightArray.length) {
i = 0;
}
}
setInterval(changeLight, 3000)
</script>
Here is my edited HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript for Programmers</title>
</head>
<body>
<h2>Happy Halloween!</h2>
<img id="pumpkin" src="pumpkinoff.gif" alt="pumpkin">
<script src="../Script/spooky.js"></script>
</body>
</html>
Incorrect capitalisation on
var currentLight = document.getElementByID('light')
Should be:
var currentLight = document.getElementById('pumpkin')
I have attached a working fiddle:
http://jsfiddle.net/11csf4k2/
It's a typo it should be:
var currentLight = document.getElementById('light'); //Not ID
It should be Id not ID:
document.getElementById('light');
Also note that you don't have element with id light on your page. It probably should be
document.getElementById('pumpkin');

stuck with javascript-html output

I am kind of stuck in weird problem. i cant find the problem with the following code
<html>
<head>
<script type="text/javascript">
// Import GET Vars
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
var tag_tag=document.$_GET['tags'];
alert(tag_tag);
document.getElementById("resultElem4").innerHTML=tag_tag;
</script>
</head>
<body>
<p id='resultElem4'></p>
</body>
</html>
its showing the string in alert but not in html when i call it like result.php?tags=cat
Put your script tag at the bottom (right before the closing body tag). The issue is that the element resultElem4 hasn't loaded when you try to reference it using getElementById.
You just move the < script > to the end of the body.
<body><p></p><script>....</script></body>

Categories