我们如何使用document.querySelectorAll来获取html页面中的所有标签

时间:2012-04-11 05:35:47

标签: javascript dom

有人建议我使用document.querySelectorAll("#tagContainingWrittenEls > *")来获取对所有书面标记的引用。然后,您可以遍历所有内容,并对列表中的每个元素执行.tagName.attributes以获取信息。

但只有在有一个名为#tagContainingWrittenEls的类时才能这样做。我认为这是一些方法

2 个答案:

答案 0 :(得分:7)

querySelectorAll函数需要selector string返回一个NodeList,它可以像数组一样迭代。

// get a NodeList of all child elements of the element with the given id
var list = document.querySelectorAll("#tagContainingWrittenEls > *");

for(var i = 0; i < list.length; ++i) {
    // print the tag name of the node (DIV, SPAN, etc.)
    var curr_node = list[i];
    console.log(curr_node.tagName);

    // show all the attributes of the node (id, class, etc.)
    for(var j = 0; j < curr_node.attributes.length; ++j) {
        var curr_attr = curr_node.attributes[j];
        console.log(curr_attr.name, curr_attr.value);
    }
}

选择器字符串的细分如下:

  • #nodeid语法是指具有给定id的节点。在这里, 使用tagContainingWrittenEls的假设ID - 您的ID很可能 不同(又短)。
  • >语法表示“该节点的子节点”。
  • *是一个简单的“全部”选择​​器。

总之,选择器字符串显示“选择id为”tagContainingWrittenEls “的节点的所有子节点。

有关CSS3选择器的列表,请参阅http://www.w3.org/TR/selectors/#selectors;它们对于高级Web开发非常重要(而且非常方便)。

答案 1 :(得分:2)

根据MDN,.querySelectorAll

  

返回与指定的选择器组匹配的文档中的元素列表(使用文档节点的深度优先预先遍历遍历)。返回的对象是NodeList。


.querySelectorAll返回与提供的选择器匹配的元素列表。

就像你在CSS中设置样式一样:你创建一个选择器,放入你想要应用于这些目标元素的属性,然后对这些元素进行样式化。

在CSS中说,您希望在<a><li><ul> idlist red ul#list li a{ color:red; } 的所有<a>样式{{1} }}。你会有这个:

<li>

实际上,<ul>id list <a>下的所有var anchors = document.querySelectorAll('ul#list li a'); 都会变为红色。

现在使用相同的选择器通过JavaScript获取相同的anchors元素

NodeList

现在<a>将包含<li>(类似于数组的结构),其中包含<ul>id下所有list的引用NodeList Array。由于<a><li>类似,因此您可以遍历它,每个项目都是<ul>id下的list {{1}} {{1}} 1 {} {{1}}。


当然,它只在代码执行时获取DOM中的元素。