Select nth child in jquery javascript

select nth child like this I want to select seconds child .

$(this).prev().children[1].removeClass("necry").addClass("necry_er");

And this HTML

<div class="reg_label">
    <div class="def">Family</div>
    <div class="necry">Necessary Field</div>
    <div class="clear">&nbsp;</div>
</div>

I expect this result:

<div class="necry_er">Necessary Field</div>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use eq() to reduce a set of matched elements to the one at the specified index.

$(this).prev().children().eq(1).removeClass("necry").addClass("necry_er");

There’s also a :nth-child selector:

$('#elementID:nth-child(2)').doSomething();

To just swap the two classes you can do:

$('.necry').toggleClass('necry necry_er');

How exactly to go about finding the element you want is a little hard to tell, as there is no explanation as to what this is or what context it is in ?

Method 2

what about something like this?

var nec = $(this).parent().find(".necry");
nec.removeClass("necry");
nec.addClass("necry_er");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x