1

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.

2
  • Why is it that you need to get the class attribute? There may be an easier way of getting that done. Commented Mar 4, 2019 at 16:49
  • Possible duplicate of Get an element by index in jQuery Commented Mar 4, 2019 at 16:51

1 Answer 1

1

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


Original Answer:

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

Sign up to request clarification or add additional context in comments.

2 Comments

You've created two jQuery objects for no reason. Use eq instead.
Thanks a lot, now I understand why it wasn't working and how to better use jQuery.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.