0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When I used console.log($(this)); it returned [span].
0

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/

3 Comments

I'm not sure what's still wrong, but even though that worked in fiddle, it didn't work for me.
@jsksma2 The structure of your markup should be the same as in the fiddle.
I'm retarded. There was other classes that were listed before the .info class. I simply needed to switch them around. Thank you all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.