Skip to content Skip to sidebar Skip to footer

Firstelementchild Doesn't Work In Internet Explorer 7...what Are My Options?

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.first

Solution 1:

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.

Solution 2:

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

Solution 3:

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

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

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

Solution 4:

try the following :

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

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

Solution 5:

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

Post a Comment for "Firstelementchild Doesn't Work In Internet Explorer 7...what Are My Options?"