user3622460
user3622460

Reputation: 1251

How to grab a class name from a specific ID using jQuery

I have an ID that has a class name such as...

<div id="nav" class="style">

I have an array containing all of my IDs called allIds. I'm trying to select an ID from it and then grab its class name. Here is what I have.

var grabClass = $("#"+allIds[0]).map(function()
{
    return this.class;
});

I would expect var grabClass to be equal to style. However, if I console log grabClass it says...

[prevObject: b.fn.b.init[1], context: document]

Not exactly sure how to make grabClass equal to ID nav's class style.

Upvotes: 1

Views: 51

Answers (2)

Vatsal
Vatsal

Reputation: 2128

Please try this

 $("#"+arr[0]).map(function(item){
    console.info(this.className);
 });

})();

We usually use map to iterate over a set of values in an array. However in this case if you iterate over set of arrays you will be getting the class of last id. And the above approach is not suitable for iterating over multiple values. You may want to have a look at this

http://jsbin.com/viyizohexa/edit?html,js,console,output

Hope this be of some help.

Happy Learning

Upvotes: 0

Thangaraja
Thangaraja

Reputation: 956

Use the below to get class name

var grabClass = $("#"+allIds[0]).attr("class")

Upvotes: 1

Related Questions