FirstElementChild does not work in Internet Explorer 7 ... what are my options?

Consider the following JavaScript:

var v; if (this.children.length > 0) { v = this.firstElementChild.value; } 

This works on modern versions of FireFox and Chrome, but this.firstElementChild.value an exception in Internet Explorer 7-8. Is there any other way to make me work for all browsers?

UPDATE - FINAL DECISION

I went with the following:

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

+8
javascript
source share
5 answers

I don’t know, maybe this.children[0].value ?

+7
source share

this.firstElementChild should work on every significant IE browser line <= 9 and Firefox 3 ( QuirksMode ).

this.children[0] will work in all important Firefox 3 browsers, except that IE <= 9 counts comment nodes as element nodes ( QuirksMode ). This may or may not be a problem for you.

The catch-all system is as follows:

 var node = this.firstChild, firstElementChild = null; for ( ; node; node = node.nextSibling) { if (node.nodeType === 1) { firstElementChild = node; break; } } 

firstElementChild will be the first child, if it exists, null otherwise. It is best to check if this.firstElementChild before executing the loop for performance reasons.

+8
source share

If your code is in the event handler and the function is associated with "attachEvent", the keyword "this" is bound to the "window" object, and not to the HTMLElement element. Try:

 function doSomething(e) { var targ; if (!e) var e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; } 

Check out http://www.quirksmode.org/js/events_properties.html .

0
source share

try the following:

 var v; if (this.children.length > 0) { v = this.firstChild; } 

althogh in modern browsers the first child will usually be a text segment

0
source share

We ran into this problem with IE11 and found that .firstChild () is a reliable fix in all browsers.

0
source share

All Articles