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
Add a ment  | 

3 Answers 3

Reset to default 8

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') 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