Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize firstChild so I don't get "x.firstChild is null or not an object"?

Tags:

javascript

In my JSP/HTML I have this:

<div id="exampleLabel"> </div>

Then in my javascript section I have a function called from an onclick like this;

function changeLabel(){
    exampleLabel.firstChild.nodeValue = 'LABEL HAS CHANGED';
}

This works fine in Chrome, does nothing in Firefox and in IE an error on page appears saying

exampleLabel.firstChild is null or not an object.

Ok I can take it that there was no firstChild so trying to do firstChild.ANYTHING would be a NPE, I can even take it that the other browsers don't just initialize it themselves like Chrome obviously does.

Question is, how do I initialize it myself so I can then go .nodeValue = "blahblah" on it?

like image 907
Nick Foote Avatar asked Jan 24 '11 11:01

Nick Foote


1 Answers

The reason it doesn't work in IE is that unlike all other major browsers, it doesn't create text nodes for whitespace in your HTML, hence your <div> that only contains a space has no child nodes in IE. I would suggest adding a text node manually, or changing an existing one.

Also, unless you've declared exampleLabel elsewhere, you're relying on a non-standard and rather icky feature of IE and Chrome that maps IDs of DOM elements to properties of the global object (i.e., you can refer to an element as a variable by its ID). This doesn't work in other browsers. What you should do instead is use 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');
like image 193
Tim Down Avatar answered Sep 30 '22 10:09

Tim Down