简体   繁体   中英

Find only first class with jQuery

In the following markup, I want to find only the first element with class .hide and change its class by clicking on .add a .

But I am unable to locate the class.

<div class="field">default</div>
<div class="field hide">find this 1</div>
<div class="field hide">and then this 2</div>
<div class="field hide">and then this 3 </div>
<div class="field hide">and then this 4</div>
<div class="field add"><a>Add more</a></div>

Here's what I'm trying:

$('.add a').click(function(e) {
    e.preventDefault();                     
    $(this).parent().siblings().find(".hide").removeClass("hide").addClass("show");
});

JSFiddle: http://jsfiddle.net/ok38wrnt/

Use :eq selector with index 0 to target only first element:

$(this).parent().siblings(".hide:eq(0)")

Working Demo

find is wrong under siblings() as the siblings are the items you want.

Use a filter instead:

You can then just add :first to the .hide to get the first match.

JSFiddle: http://jsfiddle.net/TrueBlueAussie/ok38wrnt/2/

$('.add a').click(function (e) {
    e.preventDefault();
    $(this).parent().siblings().filter(".hide:first").removeClass("hide").addClass("show");

});

which shortens to:

http://jsfiddle.net/TrueBlueAussie/ok38wrnt/5/

 $(this).parent().siblings(".hide:first").removeClass("hide").addClass("show");

You could probably use toggleClass instead, assuming you can never have both classes missing (or you will wind up with both set).

The .hide elements are siblings of the a elements' parent, so you should use siblings() with a selector. You'll also need to use :first to match the first found element. Try this:

$('.add a').click(function(e) {
    e.preventDefault();
    $(this).parent().siblings('.hide:first').toggleClass("hide show");
});

Updated fiddle

Jquery also offers first() method.

$('.add a').click(function(e) {
    e.preventDefault();                     
          $('.hide').first().removeClass("hide").addClass("show");

});

Fiddle

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