David Hope
David Hope

Reputation: 1546

jQuery: find the previous sibling with a class name?

I have a HTML code like this:

<div class="buildExMain">
    Select An Option
        <i class="fa fa-check-circle" aria-hidden="true"></i>
        <div class="buildExDrop">
            <p class="pSelection">Number 1</p>
            <p class="pSelection">Number 2</p>
        </div>
</div>

Now, I'm trying to show(); the .fa element when a .pSelection is clicked on.

I tried this jquery code with no luck:

$(document).on('click','.pSelection', function(e){
    //This doesn't work////
    $(this).prev(".fa").show();

    //doesn't work either///
    $(this).prevAll(".buildExMain.fa:first").show();
});

Upvotes: 2

Views: 3878

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176956

you element is child of div element and you want to locate element just above it .

 $(this).parent().prev(".fa").show();

Upvotes: 2

LPZadkiel
LPZadkiel

Reputation: 571

you need to understand the this scope

by looking your code that this element can only be one of those <p> elements so if you search for the sibling of this it will only look for the other <p> element you have to do something like

$('.fa').show()
or
$(this).parent().prev().show() //this is because it's exactly the previous sibling
or
$(this).parent().prev('.fa').show()

Upvotes: 1

j08691
j08691

Reputation: 208002

.prev() selects the previous sibling, which the <i> element isn't. You want:

$(this).closest("div.buildExMain").find('i.fa').show();

or, since its parent is a sibling of the <i>, you could use .parent() and .prev() together like:

$(this).parent().prev('i.fa').show();

Upvotes: 4

Related Questions