如何循环访问特定标签内的每个标签? [英] How do I loop through each tag inside of a specific tag?

查看:76
本文介绍了如何循环访问特定标签内的每个标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个函数,它有一个for循环,它贯穿特定div中的每个标签。例如,这里是div:

I am creating a function which has a for loop that runs through each tag in a specific div. for example, here would be the div:

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

是否有一个用于x中的每个标记的javascript函数,可以让我循环通过它?请记住,我不能这样做在jQuery中,每个标签可能会不同,如上所示。

is there a "for each tag in x" kind of function in javascript that would allow me to loop through it? keep in mind that I can't do this in jquery and each tag will likely be different, as shown above.

推荐答案

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

If you want all elements that are contained within a div (including children of children, etc...) and you want only elements (not other types of nodes) and you want it to work in all browsers then you can use getElementsByTagName("*") like this:

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')只是获取容器元素的一些手段 - 您可以使用任何适合于获取包含父元素的方法。

document.getElementById('container') is just some means to get the container element - you can use any method that is appropriate to get the containing parent element.

getElementsByTagName(*)可以如图所示采用通配符,以便返回节点中包含的所有元素,并且可以调用它任何元素只能从包含元素中检索元素。

getElementsByTagName("*") can take a wildcard as shown so it returns all elements contained within the node and it can be called on any element to retrieve elements only from within that containing element.

这篇关于如何循环访问特定标签内的每个标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆