Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firstElementChild doesn't work in Internet Explorer 7...what are my options?

Tags:

javascript

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?

UPDATE -- FINAL SOLUTION

I went with the following:

v = (this.firstElementChild || this.children[0] || {}).value --Thanks to all.

like image 445
dolphy Avatar asked Jun 13 '11 16:06

dolphy


People also ask

Why did ie fail?

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.

Why is Internet Explorer so slow?

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.


1 Answers

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.

like image 168
lonesomeday Avatar answered Oct 12 '22 01:10

lonesomeday