How to initialize firstChild, so I do not get "x.firstChild is null or not an object"?
In my JSP / HTML, I have this:
<div id="exampleLabel"> </div>
Then in my javascript section, I have a function called from onclick like this;
function changeLabel(){
exampleLabel.firstChild.nodeValue = 'LABEL HAS CHANGED';
}
This works fine in Chrome, does nothing in Firefox, and an error message appears on the page in IE
exampleLabel.firstChild is null or not an object.
Well, I can assume that there was no firstChild, so I'm trying to make firstChild.ANYTHING will be NPE, I can even assume that other browsers do not just initialize it on their own, as Chrome does.
The question is, how do I initialize it myself so that I can go .nodeValue = "blahblah"for it?
, IE, , HTML, <div>, , IE. node .
, exampleLabel , IE Chrome, DOM (.. ). . document.getElementById().
function changeLabel(labelText) {
var exampleLabel = document.getElementById('exampleLabel');
var child = exampleLabel.firstChild;
if (!child) {
child = document.createTextNode('');
exampleLabel.appendChild(child);
}
child.nodeValue = labelText;
}
changeLabel('LABEL HAS CHANGED');