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

后端 未结 3 783
眼角桃花
眼角桃花 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.

提交回复
热议问题