繁体   English   中英

如何遍历原始 JavaScript 中的 dom 元素?

[英]How to traverse dom elements in raw JavaScript?

我在 jQuery 中做了所有事情,但现在我要回去学习 JavaScript 正确。 那么我怎么能在 vanilla js 中做到这一点:

$('ul li a', '#myDiv').hide();
var as = document.querySelectorAll("#myDiv ul li a"),
    forEach = Array.prototype.forEach;

forEach.call(as, function(a) {
  a.style.display = "none";
});

现场示例

.getElementById , .querySelectorAll , .forEach , .call

这适用于所有现代浏览器,仅适用于旧版浏览器(如 IE8)。

您不想手动执行跨浏览器合规性,您应该为此使用 DOM shim。

您可以将ES5-shim用于.forEach支持。 你可以在这里找到一个使用 Sizzle 的 querySelectorAll polyfill

有关详细的浏览器支持,请参阅

不要听那些抱怨浏览器合规性的人。 只需使用Modernizr和朋友在一大堆 polyfills 上拍打,然后你就可以忘记 IE!

不要依赖querySelectorAll() 它在 IE <= 7 或 FF 3 中不起作用。如果你想使用 Vanilla JS,你需要学习如何编写与浏览器兼容的代码:

(function(){
    var myDiv = document.getElementById('myDiv');

    // Use querySelectorAll if it exists
    // This includes all modern browsers
    if(myDiv.querySelectorAll){
        as = myDiv.querySelectorAll('ul li a');
        for(var i = 0; i < as.length; i++)
            as[i].style.display = 'none';
        return;
    }

    // Otherwise do it the slower way in order to support older browsers

    // uls contains a live list of ul elements 
    // that are within the element with id 'myDiv'
    var uls = myDiv.getElementsByTagName('ul');

    var lis = [];
    for(var i = 0; i < uls.length; i++){
        var l = uls[i].getElementsByTagName('li');
        // l is a live list of lis
        for(var j = 0; j < l.length; j++)
           lis.push(l[j]);
    }
    // lis is an array of all lis which are within uls 
    //within the element with id 'myDiv'

    var as = [];
    for(var i = 0; i < lis.length; i++){
        var a = lis[i].getElementsByTagName('a');
        // a is a live list of anchors
        for(var j = 0; j < a.length; j++)
           a[j].style.display = 'none'; // Hide each one
    }
})();

这是一个JSFiddle 请注意,getElementsByClassName()是另一种常用的遍历方法,如果它不可用,则需要另一种方法(IE <= 8)

由于 UL 元素只能将 LI 作为子元素,因此最快的 POJS 方法是先获取所有 UL,然后再获取所有 As:

function doStuff() {
  var uls = document.getElementsByTagName('ul');
  var as;
  for (var i=0, iLen=uls.length; i<iLen; i++) {
    as = uls[i].geElementsByTagName('a');

    for (var j=0, jLen=as.length; j<jLen; j++) {
      as[j].style.display = 'none';
    }
  }
}

querySelectorAll 解决方案似乎没有任何意义,因为上述方法可能更快,代码不多,并且可以在所有浏览器中使用,回到 IE 4。

好的旧document.getElementByIddocument.getElementsByTagName应该可以帮助您入门。

您可以使用querySelectorAll来查找元素,但请记住 jQuery 可能使用额外的技巧来实现兼容性,因此这可能会有所不同。

然后您可以遍历该列表(NodeList 文档页面上显示的代码,从上面的页面链接)并设置每个元素的element.style.display = "none"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM