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

后端 未结 3 770
眼角桃花
眼角桃花 2021-02-14 17:21

Consider the JavaScript below:

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

This works in modern versions

相关标签:
3条回答
  • 2021-02-14 17:55

    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.

    0 讨论(0)
  • 2021-02-14 18:10

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

    0 讨论(0)
  • 2021-02-14 18:11

    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:

    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 http://www.quirksmode.org/js/events_properties.html.

    0 讨论(0)
提交回复
热议问题