Result of getElementById is null? - javascript

Just struggling with a Javascript class being used as a method for some cometishian code, how do I have a constructor for this code? The following code is invalid:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="Stylesheet" href="gStyle.css" />
<script type="text/javascript" language="javascript">
// Gantt chart object
function ganttChart(gContainerID) {
this.isDebugMode = true;
this.gContainer = document.getElementById(gContainerID);
if (this.isDebugMode) {
this.gContainer.innerHTML += "<div id=\"gDebug\">5,5 | 5.1</div>";
}
}
var myChart = new ganttChart("chart1");
</script>
</head>
</html>
<body>
<div id="chart1" class="gContainer"></div>
</body>
</html>
this.gContainer is null

That is because you are running the script before the page is ready, i.e. chart1 doesn't exist yet when you call new ganttChart("chart1");. Wrap the code inside window.onload = function() { } or run it at the bottom of the page.

The problem is that your script is running too early, it's looking for an element that doesn't exist in the DOM yet, either run your script onload, or place it at the end of the <body> so your id="chart1" element is there to be found when it runs.

Problem is that you run your code before the page has loaded yet, and thus the DOM element with id chart1 does not exist at the moment the code is executed.
use
window.onload = function(){myChart = new ganttChart("chart1");};

Note that using window.onload like that will override all previously stated window.onload declarations. Something along the following lines would be better:
<script type="text/javascript">
var prevOnload = window.onload || function () {};
window.onload = function () {
prevOnload();
// do your stuff here
};
</script>
Also, untill al images are fully loaded onload will not trigger, consider using jquery & $(document).ready or similar.
:)
Regards,
Pedro

Related

HTML and JavaScript in separate files - newbie alert

OK. I feel dumb! I've been trying to do something very simple and yet finding it very difficult to do or to find. All I want to do is:
have the index.html file display.
I want a separate JavaScript file that contains all of my JavaScript code. Completely separated, so I don't have any JavaScript code in my HTML file. I don't want a click event or anything fancy.
I just want the page to display Hello World! onLoad by getting it from a JavaScript function.
BTW: Seems all tutorials either put the JavaScript code in with the HTML or they want to show you how to do something fancy. I've been all over SO to no avail.
The closest I've gotten is listed below. I give up! A little help would be so appreciated.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
</head>
<body>
<script type="text/javascript"></script>
</body>
</html>
script.js:
window.onload = function() {
var result="Hello World!";
return result;
};
if you want to append to body, you can create a text node ( createTextNode() ) and then directly append that to body:
window.onload = function() {
var result = document.createTextNode("Hello World!");
document.querySelector('body').appendChild(result);
};
What you can do is print the text you want to the <body> element when the page loads. Something like this should do the trick:
window.onload = function() {
var result="Hello World!";
document.querySelector('body').innerHTML(result);
};
Or if you had a particular place on your webpage that you wanted to load this text into, you can create an element in your HTML, give it a unique id and reference it in your JavaScript:
<body>
...
<div id="myAwesomeElement"></div>
...
</body>
and in the JavaScript:
window.onload = function() {
var result="Hello World!";
document.querySelector('#myAwesomeElement').innerHTML(result);
};
In your javascript function, you can do something like this:
document.getElementById("divID").innerHTML="Hello World!";
and in your html file create a div or span or something that you want modify(in this case, the inner html content):
<body>
<div id="divID"></div>
</body>
When the function is called, it will find the dom element with the Id of "divID", and the innerHTML will be what you assign the Hello World to. You could modify other properties like css style stuff too.
If you want to grab a hold of a place where to put your file, you need to address it.
Eg.
<body>
<div id="place-for-text"></div>
</body>
And then in your script:
var elem = document.getElementById('place-for-text');
elem.innerHTML = 'Hello world.';
That is about the simplest way to do it in a way you could control some of it.
You could go more fancy and add a DOM element instead:
var elem = document.getElementById('place-for-text');
var text = document.createTextNode('Hello world');
elem.appendChild(text);
Here's a way that hasn't been shown yet.
You can remove the script tag from the head of the file since we want the js file to load up after the rest of the page. Add the script tag with the script.js source to the body.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
The script.js file looks like this:
//script. js file
!function () { document.querySelector("body").innerHTML = "hello world"; } ();
The exclamation point and the following () causes the function to run automatically upon load. For more info take a look at this question: What does the exclamation mark do before the function?
EDIT
I should also point out that document.write and .innerHTML are not considered best practice. The simplest reasons are that document.write will rewrite the page and .innerHTML causes the DOM to be parsed again(performance takes a hit) - obviously with this example it doesn't really matter since it's a simple hello world page.
An alternative to document.write and .innerHTML
!function () {
var text = document.createTextNode("Hello World");
document.querySelector("body").appendChild(text);
} ();
It's a bit of a pain, but you can write a function for the process and it's no big deal! The good news is that, with the new ecmascript 6(new JavaScript) you can turn this into a quickly written arrow function like the following:
//script.js
! function() {
var addTextNode = (ele, text) => { //create function addTextNode with 2 arguments
document.querySelector(`${ele}`).appendChild(document.createTextNode(`${text}`));
// ^ Tell the function to add a text node to the specified dom element.
}
addTextNode("body", "Hello World");
}();
Here's a JS Fiddle that also shows you how to append to other elements using the same function.
Hope this helps!
There are multiple ways to ways to solve your problem. The first way only changes your javascript. It uses the document.write() function to write the text to the document.
Here is the new javascript:
window.onload = function() {
document.write("Hello World!");
};
The second way also only changes your javascript. It uses the document.createElement() function to create a p tag and then changes the content inside it then appends it to the body.
Here is the new javascript:
window.onload = function() {
var p=document.createElement("p");
p.innerHTML="Hello World!";
document.body.appendChild(p);
};
window.onload = function() {
document.write('Hello World')
};
Returning from window.onload doesn't do anything productive. You need to call methods on the document to manipulate the page.

Attaching onclick event to element is not working

I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?
the following is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading.
To make your code work, you can try following solutions:
Place your script tag below in the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
Add an event handler to check if the window element is ready:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
Another solution would be to use jquery framework and the related document ready function
http://api.jquery.com/ready/
I think the solve you are looking for is
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).
$(function() {
//your javascript code here
});
Why using self executing function?

javascript code not work in HEAD tag

My webpage has the following code:
<html>
<head>
<title>This is test Page</title>
<script language="javascript" type="text/javascript">
document.getElementById("msg1").innerHTML = document.URL.toString();
</script>
</head>
<body>
<div class="sss">
<p id="msg1"></p>
</div>
</body>
</html>
As you now at the time the script executes the div doesn't exist but I want to put my JavaScript code only In the <head> tag and I won't put it in middle of HTML code.
But this code only works when I put the <script> tag after the <div> tag.
I use VS2010 and firefox 19.0.1
Is there anyway to put code in <head> tag?
Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.
<script language="javascript" type="text/javascript">
window.onload = function() {
document.getElementById("msg1").innerHTML = document.URL.toString();
}
</script>
The various tags in your HTML page are loaded and processed in the order in which they appear on the page. Your <script> tag is executed immediately when it is parsed in the <head>. This is before the <body> and the elements inside the <body> are parsed. So, the script tries to reference an element that is not defined at the time it is executed.
Michael Geary is right, in order to execute your code, I'd use jQuery library (a de-facto standard in JS development) and utilize the DOM ready event. This will ensure the code in the handler will execute once DOM is fully loaded.
<script>
$(function(){
$('#msg1').html(document.URL.toString());
});
</script>
I recommend to to use addEventListener like this:
<script language="javascript" type="text/javascript">
document.addEventListener("DOMContentLoaded",() => {
document.getElementById("msg1").innerHTML = document.URL.toString();
});
</script>
Your script uses dom element and must run after the dom loaded.
Wrap your code in a function and call it after dom loaded
function myfunc(){
//code here
}
window.onload = myfunc();

innerHTML not displaying

Apologies for asking such a trivial question (just learning how JS works) but I am getting a headache for next to nothing. Maybe I am tired and just don't see what I am doing but why is the below not working - i.e. value of totalBits to print in the body of the 'print' div? If I alert() it shows the value but not using the innerHTML.
<html>
<head>
<title></title>
<script type="text/javascript">
function answer(sentence){
var bitsOfString = sentence.split(" ");
var numOfBits = bitsOfString.length;
return numOfBits;
}
var sentence = prompt("OK, say something!")
var totalBits = answer(sentence);
var div = document.getElementById("print");
div.innerHTML = totalBits;
</script>
</head>
<body>
<div id="print"></div>
</body>
</html>
Because you are calling it before the element is rendered to the page. Move the script after the element is loaded or you can call your code window onload/document ready.
<html>
<head>
<title></title>
</head>
<body>
<div id="print"></div>
<script type="text/javascript">
function answer(sentence) {
var bitsOfString = sentence.split(" ");
var numOfBits = bitsOfString.length;
return numOfBits;
}
var sentence = prompt("OK, say something!")
var totalBits = answer(sentence);
var div = document.getElementById("print");
div.innerHTML = totalBits;
</script>
</body>
</html>
Have a look at your error console. You should get div is null as an error, because the element hasn't been parsed yet.
You need to put your script block after your div element or defer the execution of the script.
Most likely your JavaScritpt executes before the DOM is ready.
In other words, wrap your javascript where you manipulate the div in document.onload function or if you're happy to use jQuery: $(function(){});
You can see it working here: http://jsfiddle.net/c8tyg/
P.S.
I'm not the fan of moving the <script> blocks around because IMHO JavaScript should work regardless how you load it on the page. You're manipulating DOM - respect the game - wait for the DOM to load.

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

Categories