Cannot read property 'getElementById' of null - javascript

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>

Related

How to pass data from Node.js to html

I have a simple program and some data strings that I want to pass to HTML page that hosted locally, but I'm getting error: ReferenceError: document is not defined
There's my .js file index.js:
let some_string = "some data";
document.getElementById("dataButton").onclick = function(){
var paragraph = document.createElement("p");
var text = document.createTextNode(some_string);
paragraph.appendChild(text);
var element = document.getElementsByTagName("body")[0];
element.appendChild(paragraph);
}
And there's my HTML test.html:
<!DOCTYPE html>
<html>
<head>
<title>New title</title>
</head>
<body>
<h1>Data page</h1>
<button id="dataButton">Add data</button>
<script src="index.js"></script>
</body>
</html>
Many thanks if someone come up with idea what am I doing wrong!
Update your files to the following
let some_string = "some data";
const dataButton = document.getElementById("dataButton");
dataButton.addEventListener("click", () => {
var paragraph = document.createElement("p");
var text = document.createTextNode(some_string);
paragraph.appendChild(text);
var element = document.getElementsByTagName("body")[0];
element.appendChild(paragraph);
});
<!DOCTYPE html>
<html>
<head>
<title>New title</title>
</head>
<body>
<h1>Data page</h1>
<button id="dataButton">Add data</button>
<script src="./index.js"></script>
</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.

"Uncaught TypeError" when executing a Javascript function from a <script> HTML tag

I'm working on a basic quiz Javascript game, but when I use
document.getElementById("demo").innerHTML = "text";
I get this error message:
Uncaught TypeError: Cannot set property 'innerHTML' of null
in the Chrome Console. I have no idea why this no longer works, it has worked for me in the past. However, if I open up a new
tag, the function runs and the code works. It's only when I run the function in the same
tag.
My code is below:
<!DOCTYPE html>
<html>
<head>
<title>Study Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
function quiz() {
var rnd = Math.floor(Math.random() * 4);
document.getElementById("demo").innerHTML = rnd;
}
quiz(); //this one does not work
</script>
</head>
<body>
<p id="qarea"><p>
<p id="demo"></p>
<script>
quiz(); //this one does work
</script>
</body>
</html>
You forgot to include id in front of your ="demo" it should look like <p id="demo"> instead of
<p="demo"></p>
Second the reason the first call to quiz does not work is that your document has not loaded yet. you want to do this on pure js
<body onload="myFunction()">
Like this should work: http://jsfiddle.net/t8jnhmhg/1/ <p="demo" is wrong
It should be the following.
Where you would have to add the id attribute to the p tag.
<!DOCTYPE html>
<html>
<head>
<title>Study Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
function quiz() {
var rnd = Math.floor(Math.random() * 4);
document.getElementById("demo").innerHTML = rnd;
}
quiz(); // Will not work here because there is no such
// element with ID "demo" at this point in the page load.
</script>
</head>
<body>
<p id = "qarea"><p>
<p id = "demo"></p>
<script>
document.addEventListener( "DOMContentLoaded", function(){
quiz(); // Will work here because the DOM is loaded at this point.
});
</script>
</body>
</html>

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>

Cannot read property childNodes of null

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>

Categories