简体   繁体   中英

Traverse the DOM and get IDs

With the following HTML:

<div id="main">
    <div id="a">
        <a href=# id="a!1">qq</a>
        <a href=# id="a!3">qw</a>
        <a href=# id="a!2">qe</a> 
    </div>
    <div id="b">
        <a href=# id="b!1">qa</a>
        <a href=# id="b!2">qs</a>
        <a href=# id="b!3">qd</a> 
    </div>
    <div id="c">
        <a href=# id="c!1">qz</a>
        <a href=# id="c!2">qx</a>
        <a href=# id="c!3">qc</a>
        <a href=# id="c!4">qv</a> 
    </div>
</div>

I want to get a list of all the IDs: a, a!1, a!3, a!2, b, b!1, b!2, b!3, c, c!1, c!2, c!3, c!4

The following code kind of does that:

 var arr = $("#main > div").map(function() {
     return this.id
 });
 var aa = (arr.get().join(","));
 alert(aa);

but the alert only gives me" "a,b,c"

Is there a better way to do this that I may be missing so it will transverse the DOM of a specific container ID and pass back all the child IDs of all the elements in the container?

Use css selectors in JQuery to iterate through all, instead of direct children:

 $(function(){ $('#main *').each(function (){ var id = $(this).attr('id'); console.log(id); $('#main').append("<br /> -"+id); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="main"> <div id="a"> <a href=# id="a!1">qq</a> <a href=# id="a!3">qw</a> <a href=# id="a!2">qe</a> </div> <div id="b"> <a href=# id="b!1">qa</a> <a href=# id="b!2">qs</a> <a href=# id="b!3">qd</a> </div> <div id="c"> <a href=# id="c!1">qz</a> <a href=# id="c!2">qx</a> <a href=# id="c!3">qc</a> <a href=# id="c!4">qv</a> </div> </div> 

Just do

var arr = $("#main > div, #main > div > a").map(function() {
 return this.id
});

Your current code gives the id of direct children of #main but not of a

Just add anchors to query:

$("#main div, #main a")

Codepen

var ids = []
$("a").each(function(){
  ids.push($(this).attr("id"))
})
var total_id='';
   $('#main *').each(function(){
   total_id+=$(this).attr('id')+',';
})
console.log(total_id);

Please try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM