Reputation: 816
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
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
Reputation: 20750
Use map()
method like following.
var attributes = $("#id tag").map(function () {
return $(this).attr("attribute");
}).get();
Upvotes: 1