jakenberg
jakenberg

Reputation: 2113

Jquery: Select one class out of multiple classes with same name?

I need to choose one class from the parent element that I've clicked in a list format. All the while preventing the other classes with the same class name from showing.

So, for example:

$('ul').click(function() {
    $('li').next(".info").css({ "display" : "block" });
});

While I have .info set to display:none;

And my html code is:

<ul>
    <li><span>Guy</span></li>
    <li class="info">
        <p>This should pop up when I click on the "Guy" span.</p>
    </li>
</ul>

Although, I can't seem to figure out why it won't work/fire.

Any help would be hugely appreciated.

Upvotes: 0

Views: 3322

Answers (2)

David Thomas
David Thomas

Reputation: 253496

You're targeting the wrong element, basically. Simply use:

$('ul li').click(
    function(){
        $(this).next('li.info').show();
    });

JS Fiddle demo.

In your original code $(this) is the ul that was clicked (the click event bubbles from the clicked li or span up to the ul), and then looks for the next sibling of the ul that also has the class name of info.

My amendment works by having the target of the click event be the li, which has got a sibling element with the class of info.

Incidentally, on those occasions where jQuery doesn't work, it's helpful to do console.log($(this)) just to check your selector's matching what you think it should be matching.

Upvotes: 2

Ram
Ram

Reputation: 144739

You can bind the event to the span elements.

$(document).ready(function(){
    $('ul span').click(function() {
        // $('.info').hide()
        $(this).parent().next().show();
    });
})

http://jsfiddle.net/2mvdt/

Upvotes: 0

Related Questions