admin管理员组文章数量:1289508
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>
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.
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>
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.
Share Improve this question asked Nov 28, 2012 at 8:00 Captain DandoCaptain Dando 5072 gold badges11 silver badges30 bronze badges 2- why can't you do it in jQuery? – yoavmatchulsky Commented Nov 28, 2012 at 8:06
- 1 part of the benefit of this project to me is to learn javascript as an entry point to languages or java and jquery is too dissimilar – Captain Dando Commented Nov 28, 2012 at 8:09
3 Answers
Reset to default 8If 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')
is just some means to get the container element - you can use any method that is appropriate to get the containing parent element.
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.
Try This:
var div = getElementById('containerDivId');
for (var i = 0; i < div.childNodes.length; i++)
{
console.log(div.childNodes[i]);
}
I you want to iterate through ALL fo the tags off ALL the children (not just first level-children)
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});
});
});
本文标签: javascriptHow do I loop through each tag inside of a specific tagStack Overflow
版权声明:本文标题:javascript - How do I loop through each tag inside of a specific tag? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741409019a2377119.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论