简体   繁体   中英

Select div after parent with jQuery

<div class="col-1-3">
    <div class="click"></div>
</div>
<div class="col-1-3">
</div>
<div class="col-1-2">
</div>

Using jQuery, I need to select the col-1-2 div when a user clicks on the "click" div. I need to replace col-1-2 with col-1-3. So far, I have tried a variety of methods using parent();, next();, find(); etc. etc. Right now, I looking into:

$(".click").parent().next(".col-1-2").removeClass("col-1-2").addClass("col-1-3");

That obviously doesn't work but I am not sure where to go from here.

next will only look at the immediate next element. You need to use nextAll to test all the following siblings.

Using this instead of a selector will make sure that you are dealing with the div that was actually clicked rather than another one with the same class name.

$(this).parent().nextAll(".col-1-2").removeClass("col-1-2").addClass("col-1-3");

You may also wish to filter the results to apply the change to only the first match .

One more slightly shorter version:

$(this).parent().siblings(".col-1-2").toggleClass("col-1-2 col-1-3");

$.fn.toggleClass can be used instead or combination of removeClass + addClass : col-1-2 will be removed and col-1-3 will be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM