Hercell Yutiko
Hercell Yutiko

Reputation: 35

JQuery Hide/Show one, not all

I need help trying to figure out why this will only hide and show all of the elements for my hidden class. I've tried doing:

$("h2 > p").removeClass("hidden");

And it just won't work at all when I use that. I've also tried:

$(this).find('p').removeClass("hidden");

And that won't work at all either. As it's for an assignment, I can't edit the CSS or HTML directly and it's an introduction to JQuery, so the actual JavaScript and JQuery shouldn't be advanced at all. I just don't understand why it won't work with either of the two examples I've shown above. All I need is one of the answers to show, not every single one.

$(document).ready(function() {
    $("h2").on('mouseover', function() {
        $("p").removeClass("hidden");
    });
    $("h2").on('mouseout', function() {
        $("p").addClass("hidden");
    });
}); // end ready

This is the HTML portion including the classes that I'm trying to add and remove.

<body>
<section>
    <h1>jQuery FAQs</h1>
    <ul id="faq_rollovers">
        <li><h2>What is jQuery?</h2>
            <p class="hidden">jQuery is a library of the JavaScript functions 
            that you're most likely to need as you develop web sites.</p>
        </li>
        <li><h2>Why is jQuery becoming so popular?</h2>
            <p class="hidden">Three reasons: It's free; It lets you get more done 
            in less time; All of its functions are cross-browser compatible.</p>
        </li>
        <li><h2>Which is harder to learn: jQuery or JavaScript?</h2>
            <p class="hidden">For most functions, jQuery is significantly easier to learn 
            and use than JavaScript. But remember that jQuery is JavaScript.</p>
        </li>
    </ul>        
</section>

Note: Since the p element is hidden and you can't actually hover over it, I've elected to use the h2 element as the mouseover selector.

Upvotes: 2

Views: 186

Answers (3)

Stepan Lylak
Stepan Lylak

Reputation: 81

$( "h2" ).hover( function() {
  $(this).next().removeClass("hidden");
}, function() {
  $(this).next().addClass("hidden");
});

Upvotes: 1

juvian
juvian

Reputation: 16068

Your problem is that the p tag is not inside the h2 tag. You can either do:

$(this).siblings("p").removeClass("hidden");

Or:

$(this).parent().find("p").removeClass("hidden");

Upvotes: 2

Leah Zorychta
Leah Zorychta

Reputation: 13419

Try searching within the other h2 for the p tag:

$(document).ready(function() {
    $("h2").on('mouseover', function() {
        $(this).siblings("p").removeClass("hidden");
    });
    $("h2").on('mouseout', function() {
        $(this).siblings("p").addClass("hidden");
    });
}); // end ready

Upvotes: 1

Related Questions