Search code examples
javascriptjqueryjquery-selectors

.next() not working on all divs


jsFiddle

Above's the jsFiddle of my code. NOTE: CSS is correct, no fiddling required with that.

As you may be looking at result, there's a plus ( + ) sign in front of some addresses. When you click the topmost cell with plus sign, you see landmark text. But when you click the rest, it doesn't work. Here's the JQuery I used:

$('#landmark').click(function () {     
    $(this).next('#theLandmark').slideToggle();
});

Where #landmark is the plus (+) sign and the rest of the landmark text is #theLandmark. The HTML/CSS/jQuery is working fine, as it works with the first time. But I feel there's some more code of jQuery missing which can correct it.

Thanks!


Solution

  • The issue is because you have duplicated both the landmark and theLandmark id attributes amongst your elements. id must be unique within the page. If you convert them to class attributes your code works fine:

    $('.landmark').click(function () {
        $(this).next('.theLandmark').slideToggle();
    });
    
    <!-- one example instance... -->
    <div class='landmark'>+</div>)
    <div class='theLandmark hide'><b id='lmText'>Landmark: </b>Dharmkata</div>
    
    .landmark {
        cursor: pointer;
        display: inline-block;
    }
    .theLandmark {
        font-size: 12px;
    }
    

    Updated fiddle

    Note that #lmtext is also repeated, although that element is not affected by your JS code. You should change that to a class too.