0

Possible Duplicate:
Get attribute values as array from selection of elements using jQuery

I am trying to get the id from the list of elements

I have

<div class='test' id='123'> </div>
<div class='test' id='1243'> </div>

<div class='test' id='1223'> </div>
<div class='test' id='1423'> </div>
<div class='test' id='1223'> </div>
<div class='test' id='1253'> </div>

I want to get id for every div

I have

var idarray=[];

var id= $('.test').attr('id'); //would only get the first 123 id.

idarray.push(id)

How to I get every id to the idarray in my case? Thanks for the help

2
  • 1
    You can't have multiple elements with the same id, it is not valid HTML. Commented Nov 30, 2012 at 18:37
  • un..my codes don't have the same id..... Commented Nov 30, 2012 at 19:49

6 Answers 6

5

You can use

var idarray = $('.test').map(function(){return this.id}).get();
Sign up to request clarification or add additional context in comments.

1 Comment

You are missing .get though... idarray will be a jQuery object.
2

You can use jquery .map() function to create your array, like this:

var id = $('.test').map(function() {
   return $(this).attr('id');
}).get();

2 Comments

See dystroy's answer for a more efficient way to use the .map() method. There's no need to use jQuery inside the callback.
Yes I noticed that, anyway will leave my answer as that so to have different solutions of the same problem.
2

You can accomplish this with a simple each loop.

var idarray=[];
$('.test').each(function(){idarray.push(this.id);})

Comments

1

Use a .each loop, like this:

var idarray = [];

$(".test").each(function() {
    idarray.push($(this).attr("id"));
});

Comments

1

This is a possible solution:

ids = [];
$("div").each(function() {
    $this = $(this);
    ids.push($this.attr("id"));
});

This would result in an array of ids.

3 Comments

You can simplify this to ids.push(this.id).
Yes, but this may be more readable to the OP.
Ok, even if you want to use .attr, why do you create an extra (global!) variable $this? I prefer readability too, but that's no reason to introduce unnecessary code. At least make $this local.
1

use the below code to id in idarray

var idarray = [];
$.each($(".test"),function(index,value)
   {
idarray.push($(value).attr("id"));
   });

Check for the fiddle

http://jsfiddle.net/E8Rjs/5/ Thanks

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.