TypeError: is null (External javascript) - javascript

How do i make this code work with an external javascript file?
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script>
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
</script>
</body>
</html>
If i try to write this inside script.js file it will return this error:
"TypeError: elem is null"
OBS: I have no problems running this as inner HTML, just the external part is getting me.

If your script is run before the DOM has finished loading (and specifically the #demo element is not yet present), your call to getElementById will return null.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
So, you need to ensure that the DOM has been loaded before querying for that element.
You can either place your script tag at the end of the document (as suggested elsewhere in this post), or utilize the DOMContentLoaded event:
window.addEventListener('DOMContentLoaded', function() {
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
});

Embed your javascript file before closing the body tag, so that your javascript file runs after the page loads. Otherwise your code will run before the demo element added to the page:
<script src="external.js"></script>
And use only inner part of the inline script in the external file:
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";

Import your external javascript file at the end of the DOM. When you call your javascript file at the header, your script searches element before being loaded. That's why it gives error. Try this now!
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script src="script.js"></script>
</body>
</html>

Related

Uncaught TypeError: Cannot read property 'style' of null at prac.js:3

var hi = document.querySelector("h1");
hi.style.color = "red";
This 2 line code of giving a color to h1 using DOM is giving ERROR
Uncaught TypeError: Cannot read property 'style' of null at prac.js:3
when writing in separate javascript file whereas same 2 lines works fine in console and produces the desired effect.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Experiments</title>
<script src = "prac.js"></script>
</head>
<body>
<h1>Hey there!</h1>
</body>
</html>
Here is the demo of the issue:
var hi = document.querySelector("h1");
hi.style.color = "red";
Since it is not clear how you are using the JavaScript, so identifying the actual issues is difficult.
However, let us assume you are using JavaScript inside the same file HTML only, then the code you wrote is working fine, you can check below code snippet.
<!DOCTYPE html>
<html>
<head>
<title>Experiments</title>
<script src = "prac.js"></script>
</head>
<body>
<h1>Hey there!</h1>
<script>
var hi = document.querySelector("h1");
hi.style.color = "red";
</script>
</body>
</html>
Since mostly we are manipulating the DOM using JavaScript, this is a good practice to have JavaScript load from another file(or if you are using Javascript on the same page)at the bottom of your HTML content, just before the </body> tag, as till then most HTML content would have loaded to be used by the DOM.
If your JavaScript code is inside parc.js file, then you need to add that file just above the </body> tag, as shown in the below code.
Your HTML code
<!DOCTYPE html>
<html>
<head>
<title>Experiments</title>
</head>
<body>
<h1>Hey there!</h1>
<script src = "prac.js"></script>
</body>
</html>
Your JavaScript code
var hi = document.querySelector("h1");
hi.style.color = "red";
Probably your script runs before DOM renders. As Palash suggested, put your script tag at the end of the body tag.

Browser ignores Javascript [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
Rookie alert!
Would you tell me why my Javascript code doesn't update the message. The browser runs HTML but ignores the Javascript code. What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
</html>
You're running the Javascript before you've loaded the body, the message element doesn't exist yet. Either move the script to the end of the <body>, or change the last line to:
window.onload = updateMessage;
so that the function will be loaded after the HTML is loaded.
If the <script> tag is in the <head> element, it gets executed before the HTML elements in the <body> are created. You can put your script tag inside the <body> element, at the end of it, to solve the issue.
Assuming you don't simply have javascript disabled, you could add a window.onload=function(){ surrounding your code.
window.onload=function(){
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
}
The reason for doing this is because your javascript code is inside your <head>. Thus, the javascript is loaded before the body. When the browser attempts to execute the javascript code, the message element isn't loaded yet and doesn't exist. By adding window.onload=function(){ to surround your code, your entire code will wait until the body is loaded before executing.
When you call your javascript code, the 'message' element isn't already there. I would suggest one of the following two things:
+Put your javascript code at the end of the body ( note that it only need to be after 'message', but putting it at the end is generally the best option )
+Replace your call with window.onload = updateMessage, which will wait until all the page is loaded to execute your javascript
There are already lots of duplicate answers here but there is another way, especially if you want to keep your Javascript code in a script tag in the head. And that is, wrap your Javascript function call in setTimeout -- this causes the function to be executed after the DOM has been parsed, but before the entire window has been loaded.
It's a neat little trick that can be used when you don't have a framework's (such as jQuery) document/ready functionality. window.onload or putting the script at the bottom might cause significant delays if there is lots of heavyweight content (large images?) in the page.
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
setTimeout(updateMessage);
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
</html>
Notice I have added a very large image to the page, but the updated message displays before the image fully loads.
If however instead of setTimeout(updateMessage); you use window.onload = updateMessage; as suggested in the currently accepted answer, your message will not get updated until the entire image loads (if you try this out, make sure you do a hard refresh after the first time so you are not getting it from your cache). Same goes for moving the script too far down the page (below the very large image for instance) as below. I honestly think, if you don't have a framework's document/ready functionality, using setTimeout in a script block in the head is the best solution.
MESSAGE NOT UPDATED UNTIL AFTER IMAGE LOADS:
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>
You are trying to make the changes before the DOM is loaded. See the code below,
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>

Getting entire HTML in JavaScript

I'm trying to get the entire HTML of a page, but it seems that the text stops after </head>. The following code is essentially how I tested this. What am I doing incorrectly here?
<html>
<head>
<script>
document.onload = showHTML();
function showHTML() {
html = document.documentElement.innerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
Okay here is a complete working answer... after checking already posted answer I realized it didn't work for multiple reasons..
First you need to put a function in the onload event. The onload event is written without uppercases.
Also! you need to put the event on the window object as such:
window.onload = showHTML;
Here is a fiddle. Notice on the left that it isn't wrapped inside onload. It's unwrapped in head like your code should be.
http://jsfiddle.net/4zsGH/2/
You should have something like this:
<html>
<head>
<script>
window.onload = showHTML;
function showHTML() {
var html = document.documentElement.outerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
Take off the parenthesis from document.onLoad = showHTML();
What's happening is showHTML() is being called right away, before the rest of the document is being loaded. Taking off the parenthesis means the function is being set to the onLoad callback.
Try:
<html>
<head>
<script>
document.onload = showHTML;
function showHTML() {
var html = document.documentElement.outerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
When you wrote document.onLoad = showHTML(); you didn't assign the reference to showHTML function to document.onLoad but you assigned the value returned by that function i.e. undefined (because you called it). I also changed innerHTML to outerHTML.
Also document.onload shouldn't be written in camel case.
Writing var html = … isn't essential but it wouldn't run in strict mode. Without it you create a html property on global object window implicitly.
I think this is what you are looking for:
document.onLoad = showHTML();
function showHTML() {
var html = document.documentElement.innerHTML;
alert(html);
}
http://jsfiddle.net/skhan/4zsGH/

Why javascript doesnt get element by id when that element is below script tag?

I'm learning javascript and studying this example:
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
My question is why doesn't the script work properly when the line with <p id="p1">Hello World!</p> is below the script, and what happens during its execution? Thank you.
Because the JavaScript is run when the browser encounters it, when compiling/rendering the page; not once it's finished rendering the page. So, if the element appears after the script it doesn't (yet) exist at the point at which the JavaScript is run.
You could, though, create a function and have that function run once an element has loaded, for example:
<script>
function bodyLoaded(){
document.getElementById('p1').innerHTML = 'New text!';
}
</script>
<body onload="bodyLoaded()">
<!-- HTML here... -->
<p id="p1"></p>
</body>
Javascript is an interpreted language. 'interpreted' means that it:
"executes instructions directly, without previously compiling a
program into machine-language instructions"
Hence because the javascript interpreter executes instructions on the page line by line (starting from the top of the page), the order in which code is defined is crucial. So in your example the paragraph element has to be defined before your call to getElementById.
Elements must be defined in order for JavaScript to recognize them. If you chose to put your JavaScript inside the <head> tag, then you can do this with the window.onload event. This can be done several ways.
//Obtrusive JavaScript
<html>
<head>
<script>
function loadMe(){
var doc = document;
function E(e){
return doc.getElementById(e);
}
E('p1').innerHTML = 'New text!';
}
</script>
</head>
<body onload='loadMe'>
<p id='p1'>Hello World!</p>
</body>
</html>
/* Unobtrusive JavaScript ---> the way you should learn it in my opinion
Notice there's no onload attribute in the body tag. Also, I use onload
instead of window.onload, because window is implicit, just as document
is a property of window as well.
*/
<html>
<head>
<script>
onload = function(){
var doc = document;
function E(e){
return doc.getElementById(e);
}
E('p1').innerHTML = 'New text!';
}
</script>
</head>
<body>
<p id='p1'>Hello World!</p>
</body>
</html>
Of course, you should use external JavaScript whenever possible.

Simple jQuery .load Example Not Working

I'm sure this is a fairly basic question, but I'm relatively new to jQuery so was hoping someone might be able to help.
Basically, I need to load an HTML snippet into a page. This works fine when the snippet contains just HTML, but not when it contains a script.
I've stripped down my code to the bare minimum for clarity. This is index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<h1>Heading</h1>
<div id="banner"></div>
<script>
$(document).ready(function(){
$('#banner').load('banner.html');
});
</script>
</body>
</html>
And banner.html contains just the following (as an example):
<h2>Subheading</h2>
<script>
document.write('Hello');
</script>
The script is executed, but for some reason it strips out the rest of the HTML in both index.html and banner.html (i.e. it just displays "Hello" and nothing else).
Any help greatly appreciated!
document.write after the page has load writes to the document, and at the same overwrites everything else currently in the document, that's why you end up with only the string "hello".
Just remove the document write :
<h2>Subheading</h2>
<p id="test"></p>
<script>
document.getElementById('test').innerHTML = 'hello';
</script>
that is becuase when banner.html is loaded .. the script inside banner.html get executed, which writes "hello" in your document(the document here is your entire index.html)
one way to understand this is by replacing certain content of banner.html rather than the whole document.
banner.html
<h2>Subheading</h2>
<div id="divID"></div>
<script>
$('#divID').html('hello'); //using jquery .. gets the element with id as divID and replace the HTML
</script>
here i am replacing just the div whose id is "divID" rather than replacing the enrite document

Categories

Resources