Joe Shanahan
Joe Shanahan

Reputation: 816

jQuery: Retrieve named attribute from multiple elements

I have a bunch of elements that I wish to convert to an array of attributes and I'm using the following code:

var attributes = [];
$("#id").find("tag").each(function() {
    attributes.push($(this).attr("attribute"));
});

Is there a neater way to do this? Feels like I'm using shears to trim my finger nails.

I've been using d3 recently, it feels like there could be a way to do this in a way that would look like var attributes = $("#id").find("tag").attr("attribute"); but this just sets the variable to the attribute of the first element in the selection.

Upvotes: 3

Views: 2794

Answers (3)

SANJAY ARAKERI
SANJAY ARAKERI

Reputation: 49

To targe every element inside html page using native method hasAttribute.

var attributes = [];
$("*").each(function(index,element)
{  
    if($(element)[0].hasAttribute("id"))
    {   
       attributes.push($(this).attr("id")); 
    }
});

alert(JSON.stringify(attributes)); 

To target specific elements in a page . add some elements like p,label,h1 etc in html page and try following.You can also provide id or class names in jQuery selector like $(".className , #id , tagName ") etc .

var attributes = [];
$("p,h1,label").each(function(index,element)
{  
   if($(element)[0].hasAttribute("id"))
   {
      attributes.push($(this).attr("id"));
   }
});

alert(JSON.stringify(attributes));  

Third you can use map mathod . map method will return array .

attributes = $("p,h1").map(function()
{
   return $(this).attr("id");
}).get();

alert(JSON.stringify(attributes));

Second & third are better . They Will target specific elements .

Upvotes: 1

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

Use map() method like following.

var attributes = $("#id tag").map(function () {
    return $(this).attr("attribute");
}).get();

Upvotes: 1

Satpal
Satpal

Reputation: 133453

You can use .map() along with .get()

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

var attributes = $("#id tag").map(function() {
    return $(this).attr("attribute");
}).get();

Upvotes: 4

Related Questions