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

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

提交回复
热议问题