Arpad Flandorffer
Arpad Flandorffer

Reputation: 145

How to get attributes from specific objects in an array using jQuery?

I've been trying to get the class attribute from an label element listed on an array.

I have two label elements with specific classes like so:

<label class="lblClass1">Answer 1
    <input type="radio" name="radioQ-1">
</label>
<label class="lblClass2">Answer 1
    <input type="radio" name="radioQ-1">
</label>

I'm looking for all the label elements with the following jQuery code:

var lblClass = $('label');

This will return both label elements as objects in an array, however I cannot get the attributes from a specific object in this array.

Let's say I want the class attribute from the second element in this array AKA lblClass2, I've tried something like this:

var ckbClass = $('label')[1].attr('class');

This approach gives me an error, however something like:

var ckbClass = $('label').attr('class');

Will successfully return the class attribute from the first elementon the array AKA lblClass1. This is probably due to some syntax error on jQuery that I don't understand yet.

Upvotes: 1

Views: 79

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Edit A better approach would be $('label').eq(1).attr('class');


Original Answer:

You would use something like: $($('label')[1]).attr('class');

Upvotes: 1

Related Questions