Cannot read property childNodes of null - javascript

Why do I get the error cannot read property childNodes of null? This code is obtained from the book SAMS Teach Yourself Javascript in 24 hours.
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<script>
var text = "";
var pElement = document.getElementById("toDoNotes");
for (var i=0; i < pElement.childNodes.length; i++) {
if (pElement.childNodes[i].nodeType ==3){
text += pElement.childNodes[i].nodeValue;
};
}
alert("The paragraph says:\n\n" + text);
</script>
</head>
<body>
<h1>Things To Do</h1>
<ol id="toDoList">
<li>Mow the lawn</li>
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
</body>
</html>

Your code needs to be executed after the page is completely loaded. You can use the onload event to do this.
Your script is added to the head element, and this will get executed before the toDoNotes element is added to the dom. Thus document.getElementById("toDoNotes") will return a null value.
<html>
<head>
<title>To-Do List</title>
<script>
function init(){
var text = "";
var pElement = document.getElementById("toDoNotes");
for (var i=0; i < pElement.childNodes.length; i++) {
if (pElement.childNodes[i].nodeType ==3){
text += pElement.childNodes[i].nodeValue;
};
}
alert("The paragraph says:\n\n" + text);
}
</script>
</head>
<body onload="init()">
<h1>Things To Do</h1>
<ol id="toDoList">
<li>Mow the lawn</li>
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
</body>
</html>

The JavaScript function is executed before DOM are created. Include the script tag at the end before body tag ended.
YOUR CODE:
<head>
<script></script>
</head>
<body>
</body>
CORRECT WAY:
<head>
// Not here
</head>
<body>
<!-- right before <body> tag is closed -->
<script></script>
</body>

Because, when your JS is executed, your DOM objects are not created yet. So put your script after the body.
</body>
<script>
//---your JS code---
</script>
</html>

Related

Cannot read property 'getElementById' of null

I'm writing a simple Cat Clicker app with HTML and JS, but this code keeps spitting 'Cannot read property 'getElementById' of null' error.
What's wrong with it??
<!DOCTYPE html>
<html>
<head>
<title>Cat Clicker</title>
<script>
'use strict'
var cat = document.getElementById("cat");
var counter = document.getElementById("counter");
var meter = 0;
function incClick() {
meter++;
counter.innerHTML = meter;
};
cat.addEventListener('click', incClick);
</script>
</head>
<body>
<p id="counter" >0</p>
<img id="cat" src="img/cat1.jpg" alt="cat">
</body>
</html>
I've corrected a few issues below. You need to use document rather than document.body. You need to ensure the dom has completed loading so I added a content loaded event listener.
<!DOCTYPE html>
<html>
<head>
<title>Cat Clicker</title>
<script>
'use strict'
document.addEventListener("DOMContentLoaded", function() {
var cat = document.getElementById("cat");
var counter = document.getElementById("counter");
var meter = 0;
function incClick() {
meter++;
counter.innerHTML = meter;
};
cat.addEventListener('click', incClick);
});
</script>
</head>
<body>
<p id="counter" >0</p>
<h1 id="cat" src="img/cat1.jpg" alt="cat"></h1>
</body>
</html>
You need to include <script> Tags after the body of the HTML DOC or at least at the very end of your HTML content.
This is b/c how the DOM operates. It loads everything in a sequential order, thus your script it attempting to target an element which doesn't yet exist in the DOM
Just put your script tag after the body tag because I think the problem is that the DOM is rendering after the script runs.
And you can also use document.getElementById instead of document.body.getElementById
just use onclick="incClick()" in your h1 tag , or u can define it as image
<!DOCTYPE html>
<html>
<head>
<title>Cat Clicker</title>
</head>
<body>
<p id="counter">0</p>
<h1 id="cat" src="img/cat1.jpg" alt="cat"></h1>
<p class="counter">0</p>
<img class="cat" src="img/cat2.jpg" alt="cat">
<!--
You need to put the script tag at the end of the body
Because the document must first be created
-->
<script>
'use strict'
var cat = document.getElementById("cat");
var counter = document.getElementById("counter");
var meter = 0;
function incClick() {
meter++;
counter.innerHTML = meter;
};
cat.addEventListener('click', incClick);
</script>
</body>
</html>
This worked for me. You are mistakenly calling getElementById from document.body where it doesn't exist. It is document.getElementById:
<!DOCTYPE html>
<html>
<head>
<title>Cat Clicker</title>
<script>
'use strict'
var cat = document.getElementById("cat");
var counter = document.getElementById("counter");
var meter = 0;
function incClick() {
meter++;
counter.innerHTML = meter;
};
cat.addEventListener('click', incClick);
</script>
</head>
<body>
<p id="counter">0</p>
<h1 id="cat" src="img/cat1.jpg" alt="cat"></h1>
<!-- <p class="counter">0</p>
<img class="cat" src="img/cat2.jpg" alt="cat"> -->
</body>
</html>

JavaScript assistance with code

I wrote these few lines of code and would like the text to change once the button is pressed but its not working. Could you please find out the problem?
var omari = "Omari Lamar";
function omari (){
el = document.getElementById('slice');
el.textContent = omari + "Is a computer Programmer!";
}
<html>
<head>
<title></title>
</head>
<body>
<h1>Title Example</h1>
<button onclick="omari();">Click me</button>
<div id="slice">
sample text
</div>
<script src="app.js"></script>
</body>
</html>
Change the code to:
var omariName ="Omari Lamar";
function omari (){
el = document.getElementById('slice');
el.textContent = omariName + "Is a computer Programmer!";
}
Here you go, Your function name and variable name were the same
var omary ="Omari Lamar";
var omari = function(){
var el = document.getElementById('slice');
el.innerHTML = omary + "Is a computer Programmer!";
};
<html>
<head>
<title>
</title>
<script src="app.js"></script>
</head>
<body>
<h1>Title Example</h1>
<button onclick="omari();">Click me</button>
<div id="slice">
sample text
</div>
<script src="app.js"></script>
</body>
</html>
this is the problem:
you have a variable named omari and a function name omari. so, when you try calling the function omari, javascript actually looks at the variable definition, and not the function. just give them different name.
try the code below.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<script>
var _omari ="Omari Lamar";
function omari(){
el = document.getElementById('slice');
el.innerHTML = _omari + " Is a computer Programmer!";
}
</script>
<h1>Title Example</h1>
<button onclick="omari();">Click me</button>
<div id="slice">
sample text
</div>
</body>
</html>

Using javascript to replace the html content

I am trying to replace the content of id='js' with javascript, but this is not working for me. here is the code.
<html>
<head>
<title></title>
<script type="text/javascript">
var ball = 0;
function count_balls(ball){
var count = ball + 1;
return count;
}
document.getElementById('js').innerHTML = count_balls(0);
</script>
</head>
<body>
<p id='js'>Result Here</p>
</body>
</html>
Because the element is not initialized yet, it's not working. You can either move the javascript to the end of the HTML (preferred) as shown below:
<html>
<head>
<title></title>
</head>
<body>
<p id='js'>Result Here</p>
<script type="text/javascript">
var ball = 0;
function count_balls(ball){
var count = ball + 1;
return count;
}
document.getElementById('js').innerHTML = count_balls(0);
</script>
</body>
Or you can use jquery document.ready to achieve the same thing.

How to delete the contents of a paragraph with javascript

I have a paragraph that I'd like to delete the contents of.
document.getElementById(id).innerHTML = "";
doesn't seem to be working. Does anyone have a better solution?
Here's an example
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
</body>
</html>
but the words in the paragraph are not removed. Thanks in advance to anyone that can help.
<!DOCTYPE html>
<html>
<head>
<!-- here the p tag doesn't exist yet -->
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
<!-- however here it does exist -->
</body>
</html>
how to fix it ?
// only use this if you can't move your javascript at the bottom
window.onload = function() {
document.getElementById("p").innerHTML = "";
}
or move your javascript at the end of the page (this is the preferred one as javascript should always be loaded at the end of the page)
<!DOCTYPE html>
<html>
<head>
<!-- here the p tag doesn't exist yet -->
</head>
<body>
<p id="p">
words
</p>
<!-- however here it does exist -->
<script>
document.getElementById("p").innerHTML = "";
</script>
</body>
</html>
Be aware you use something that's not in W3C spec... (removing by innerHTML='')
var elem = document.getElementById(id);
if (!elem) {
console.log("No element for id:"+id);
} else {
elem.innerHTML="";
console.log("Should work");
}
Make it a function and add with the body onload event it should work:
<script>
function empty(){
document.getElementById("p").innerHTML = "";
}
</script>
<body onload='empty()'>
<p id="p">
words
</p>
</body>
I have often use jQuery for this function but, since you are seeking for pure javascript syntax. you will want to use this code:
document.getElementById("p").remove();
function funboi()
{
document.getElementById("p").innerHTML = "";
}
<!-- Just add a button. Works fine-->
<p id="p">
words are amazing
</p>
<button onclick="funboi()">click to delete</button>

javascript appending in a for loop not working but alering is

I am trying to append to a string in a for loop. I can alert each value bieng looped but i cant append for some reason:
<html>
<head>
<script type="text/javascript" language="javascript">
function doIt(){
var styleSheet = document.styleSheets[0];
var css="";
for (i=0; i<=styleSheet.cssRules.length; i++)
{
css += styleSheet.cssRules[i].cssText;
//alert(styleSheet.cssRules[i].cssText); //WORKS
}
}
</script>
<style type="text/css">
.container{display:none;}
.markup-container{color:#404040;}
.title{text:decoration:underline;}
.body{color:#000;}
</style>
</head>
<body>
<input type="button" id="button" onmousedown="doIt()">
<div class="container">
<div class="markup-container">
<div class="title">This is a title with some markup</div>
<div class="body">This is the body with some markup and it's longer ^^</div>
</div>
</div>
</body>
</html>
Your for loop is off by one :)
for (i=0; i<=styleSheet.cssRules.length; i++)
//should be:
for (i=0; i<styleSheet.cssRules.length; i++)
When this happens at the end:
styleSheet.cssRules[styleSheet.cssRules.length].cssText
You'll get an error, because you're one past the length of the array, and styleSheet.cssRules[i] is undefined, resulting in an error when you try to access the .cssText property on it.

Categories