tags:

views:

334

answers:

5

How do you get the id's in a div?

<div id="container">
   <div id="frag-123">ass</div>
   <div id="frag-123">ass</div>
   <div id="frag-123">ass</div>
</div>

Thanks!

+1  A: 

You can use

attr('id')
middus
A: 
$('div', $('div#container')).each(function() {
    console.log($(this).attr('id')); 
});
knoopx
+8  A: 

There are multiple ways to do this. You can use map():

var ids = $("#container").children().map(function(n, i) {
  return n.id;
});

or each():

$("#container").children().each(function(n, i) {
  var id = this.id;
  // do something with it
});

etc

cletus
+1 - beat me to it :)
Russ Cam
$("div#container").children('div').map(function(){ return this.id });
knoopx
Will this also get the dynamically created DIVS using JQuery? Thanks!
Martin Ongtangco
If the divs are created and in the DOM at the time you run this, yes.
cletus
hi cletus, thank you again for the help. I have a follow-up question through this link: http://stackoverflow.com/questions/1457637/how-do-you-pass-an-array-string-to-a-web-service-via-jquery
Martin Ongtangco
Good one.Little typo: it should be var ids = ...function(i,n) instead of ...function(n,i)
Raghav Khunger
A: 

to get them as an array of strings

var ids = $.map($('#container div'), function(n,i) {
              return n.id
          });
Russ Cam
A: 

i'm trying to pass it to my webmethod as a string[] array. But im having trouble with it.

var ids = $.map($("#container-1").children(), function(n, i) {

                                    return n.id;

                             });

                     $.ajax({
                         type: 'POST',
                         url: 'Loader.asmx/Active',
                         data: "{'tab':'" + ids + "'}",
                         contentType: 'application/json; charset=utf-8',
                         dataType: 'json',
                         success: function(msg) {
                         }
                     });
Martin Ongtangco
data is not an string is a javascript array, jquery internally transforms it to string: data: { 'tab': ids }
knoopx