2

I am trying to make array of ids of all DIVs using the below code,

var srcs = $.map($('div'),function()
{
  return this.prop('id');
});
alert(srcs);

Below is my HTML code..

<div id='d1'></div>
<div id='d2'></div>
<div id='d3'></div>
<div id='d4'></div>

Here is the fiddle link,
http://jsfiddle.net/HcL82/

4 Answers 4

4

.map() is applied to a selector; like this:

var ids = $('div').map(function(){
  return this.id;
});

console.log(ids); // ['d1', 'd2', 'd3', 'd4']
Sign up to request clarification or add additional context in comments.

Comments

2

I would do it like this:

var srcs = $('div').map(function(){
     return $(this).prop('id');
   }).get();
alert(srcs);

2 Comments

What is the advantage of using get() here.. Thanks
The get() converts the returned values to a basic array. You may not need that part. Sorry for the confusion.
1

Like this:

var srcs = $.map($('div'), function(obj) {
    return $(obj).attr('id');  
});

1 Comment

Note that you can replace the return statement with return obj.id;
1
var srcs = $.map($('div'),function(n,i)
   {
     return $(n).prop('id');
   });
alert(srcs.join(','));

Working demo - http://jsfiddle.net/MpkLs/

2 Comments

What makes difference if I use join() in this scenario. Thanks
Join flattens the array and returns a string with each array element value separated by the character that is passed into the 'join' function. I used it at then end of this example just to demonstrate that everything had worked as it should via the value in the 'alert' statement. You wouldn't need to use 'join' to do what you wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.