最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - firstElementChild doesn't work in Internet Explorer 7...what are my options? - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Jun 13, 2011 at 16:48 dolphy asked Jun 13, 2011 at 16:24 dolphydolphy 4721 gold badge6 silver badges14 bronze badges 1
  • 2 The || {} doesn't make much sense. – Ally Commented Dec 10, 2013 at 10:00
Add a comment  | 

5 Answers 5

Reset to default 8

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.

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

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.

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

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

发布评论

评论列表(0)

  1. 暂无评论