如何遍历特定标签内的每个标签?

时间:2012-11-28 08:00:09

标签: javascript html

我正在创建一个具有for循环的函数,该循环遍历特定div中的每个标记。例如,这里将是div:

<div>
 <input id="inputid"></input>
 <a id="aid"></a>
 <div id="divid"></div>
</div>

在javascript中是否存在“for x中的每个标记”类型的函数,这将允许我循环它?请记住,我不能在jquery中执行此操作,并且每个标记可能会有所不同,如上所示。

3 个答案:

答案 0 :(得分:7)

如果你想要一个div中包含的所有元素(包括孩子的孩子等等)并且你只想要元素(不是其他类型的节点)并且你希望它在所有浏览器中工作那么你可以使用getElementsByTagName("*")喜欢这样:

var allTags = document.getElementById('container').getElementsByTagName("*");
for (var i = 0, len = allTags.length; i < len; i++) {
    // allTags[i] is an element within the container object
    // allTags[i].id is the id of the element (if there is one)
}

document.getElementById('container')只是获取容器元素的一些方法 - 您可以使用任何适合获取包含父元素的方法。

getElementsByTagName("*")可以使用通配符,如图所示,它返回节点中包含的所有元素,并且可以在任何元素上调用它,以仅从包含该元素的元素中检索元素。

答案 1 :(得分:1)

试试这个:

var div = getElementById('containerDivId');
for (var i = 0; i < div.childNodes.length; i++)
{
    console.log(div.childNodes[i]);
}

答案 2 :(得分:-1)

我想要遍历所有孩子的所有标签(不仅仅是第一级孩子)

jQuery(element).find('*').each( function (index,value) { 
        $.each(value.attributes, function(i, attrib){
        var name = attrib.name,
           value = attrib.value;
         // do whatever you wann do 
         console.log({ attributeName : name, attributeValue: value});
      });
});