Consider the JavaScript below:
var v;
if (this.children.length > 0) {
v = this.firstElementChild.value;
}
This works in modern versions of FireFox and Chrome but this.firstElementChild.value
throws an exception in Internet Explorer 7-8. Is there another way for me to get this to work for all browsers?
I went with the following:
v = (this.firstElementChild || this.children[0] || {}).value
--Thanks to all.
Internet Explorer's fallMicrosoft did not follow the guidelines set by the World Wide Web Consortium – the organisation that establishes standards for web technologies – and so Internet Explorer would often make web pages look different on its own browser than on others like Opera and Firefox. Competitors arose.
Internet Explorer, after an excessive amount of usage over time, can be quite slow because of all the configurations and the settings that the user may or may not have applied at their own will. In Internet Explorer menu, click Tools, and then Internet Options. Select the Advanced tab and click Reset.
this.firstElementChild
should work in every significant browser bar IE <=9 and Firefox 3 (QuirksMode).
this.children[0]
will work in every significant browser bar Firefox 3, except that IE <=9 counts comment nodes as element nodes (QuirksMode). This may or may not be an issue for you.
The catch-all system is this:
var node = this.firstChild,
firstElementChild = null;
for ( ; node; node = node.nextSibling) {
if (node.nodeType === 1) {
firstElementChild = node;
break;
}
}
firstElementChild
will then be the first element child if one exists, null
otherwise. It would be best to see if this.firstElementChild
exists before doing the loop, for performance reasons.
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