Reputation: 215
I want to apply the toggle function to the two buttons separately. However, when I use the code below, it toggles both content under each button. How can I separate them so that when I click the first button only the content under it will be toggled?
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
<script>
$("button").click(function () {
$("p").toggle();
});
</script>
</body>
</html>
Upvotes: 1
Views: 801
Reputation: 206102
Simple: use nextUntil()
.
Will select all the next elements until matched element reached (in your case the next button
):
$("button").click(function () {
$(this).nextUntil('button').toggle();
});
Upvotes: 2
Reputation: 207901
Why have two paragraph tags for this? Make your HTML:
<button>Toggle</button>
<p>Hello</p>
<button>Toggle</button>
<p>Hello</p>
and your jQuery:
$("button").click(function () {
$(this).next('p').html( ($(this).next('p').html()=='Hello')?'Good Bye':'Hello');
});
Upvotes: 0
Reputation: 82903
Try this:
$("button").click(function () {
$(this).nextAll("p:lt(2)").toggle();
});
Upvotes: 1