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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With