ReRed
ReRed

Reputation: 373

How can I select the element under a given element in jQuery?

So I have the following problem: I have a HTML content which I'm not allowed to change, I can only use jQuery. If I click on a h1 tag, I should display the tag with a given class (current) and slide down the content. How can I select the content under the h1 tag? This is my current solution:

<script type="text/javascript">
$("document").ready(function() {
    $("div").hide();
    $("h1").click(function() {
        if ($(this).is(':visible')) {
            $(this).("div").slideDown();
            $(this).addClass('current');
        }
    });
});
</script>

But there is the problem. How can I know which h1 tag it is? Here is the HTML-Text:

<h1 class="bar">Überschrift 1</h1>
<div class="content">
    <p>Lorem ipsum dolor sit amet...</p>
</div>
<h1 class="bar">Überschrift 2</h1>
<div class="content">
    <p>Morbi tincidunt, dui sit amet...</p>
</div>

Upvotes: 1

Views: 49

Answers (1)

StudioTime
StudioTime

Reputation: 23959

Try this:

$(this).next().slideDown().addClass('current');

.next() gives you the next element, then you can chain the .addClass('current') onto the end of it

Upvotes: 2

Related Questions