How can I get the correct selector on Click?

I need your help.

I am trying to get the correct selector when I click, but the problem is displaying all the parent divs of it.

<div class="item">
    <a href="">element1</a> <span>span1</span> <br>
    <a href="">element10</a> <span>span10</span> <br>
</div>

<div class="item">
    <a href="">element2</a> <span>span2</span><br>
    <a href="">element20</a> <span>span20</span><br>
</div>

<div class="item">
    <a href="">element3</a> <span>span3</span><br>
    <a href="">element30</a> <span>span30</span><br>
</div>

<div class="item">
    <a href="">element4</a> <span>span4</span><br>
    <a href="">element40</a> <span>span40</span><br>
</div>

JS Code:

$('.item span').hide();

$('.item a').click(function(){

    // hide all span
    var $this = $(this).parent().find('span');
    $(".item span").not($this).hide();

    // here is what I want to do
    $this.toggle();

});

example: http://jsfiddle.net/BGSyS/637/

I would like when I click on "Element10", only span10 is shown, not span1. Can you help me? thanks.

+4
source share
2 answers

Try using .next()in this context to facilitate your work,

var items = $('.item span').hide();
$('.item a').click(function(e){
    e.preventDefault();
    items.not($(this).next('span').toggle()).hide();
});

Demo

+2
source

Try the following:

$('.item span').hide();

$('.item a').click(function(e){
    e.preventDefault();
    $('.item span').hide();
    $(this).next('span').toggle();    
});
0
source

Source: https://habr.com/ru/post/1605938/


All Articles