Select nth child in jquery javascript

随声附和 提交于 2019-12-02 19:29:32

问题


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>

回答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 ?




回答2:


what about something like this?

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


来源:https://stackoverflow.com/questions/11618301/select-nth-child-in-jquery-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!