user5818995
user5818995

Reputation:

Why is the selection not extended when using `add()` in jQuery

I have a form with 3 input fields. The HTML looks like:

<label>Name </label> <input .../>
<label>Email </label> <input .../>
<label> Password </label><input .../>

I left the code for input tags because that's not relevant here. Now in the script part, I want to add a class 'colored' in some of my <label> tags that color the background of those labels with #333 (well, don't mind the goal. I know it's super easy to select my labels by simply wrapping the required labels in a class or id. But I am practising, want to select elements using more complex jQuery selectors). I tried this:

$('label:nth-child (1)').add ('label:nth-child (2)').addClass ('colored')

But it only colored the first label (label having value Name). What's wrong?

Upvotes: 2

Views: 27

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

This is a common misunderstanding. For the purposes of the index used with :nth-child, it doesn't matter whether the element is a label or not. There is no label:nth-child(2) in your markup, because the :nth-child(2) element is an input (assuming what you've shown are at the beginning of their parent element).

You can achieve what you're trying to do via jQuery's .eq method:

$('label:nth-child (1)').add($('label').eq(1)).addClass('colored');

(unlike :nth-child, indexes for .eq are zero-based)

Or more likely:

$('label').eq(0).add($('label').eq(1)).addClass('colored');

Upvotes: 1

Related Questions