Reputation: 1582
I'm trying to set up a click function whereby when you click on a h3
tag it will find all the next instances of em
and br
UNTIL the next instance of h3
and show them. There's a jsFiddle demo here: http://jsfiddle.net/nm4a8njn/ and the markup below:
HTML:
<div class="col span_1_of_2">
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
</div>
CSS:
.span_1_of_2 h3 {
cursor: pointer;
}
.span_1_of_2 em {
display: none;
}
.span_1_of_2 br {
display: none;
}
jQuery:
$(document).ready(function () {
$(".span_1_of_2 h3").click(function () {
$(this).closest(".span_1_of_2").find("em").show();
});
});
But as you can see, when you click on a h3
tag this is showing ALL instances of em
, whereas I only want to target the em
and br
elements up until the next instance of h3
. If this is at all possible? Any suggestions would be greatly appreciated!
Upvotes: 0
Views: 114
Reputation: 666
AmmarCSE made it faster but anyways - here is a jQuery function .nextUntil()
that will 1) fin all elements that is next to current element and 2) filter result set. Here's the working example:
$(document).ready(function () {
$(".span_1_of_2 h3").click(function () {
$(this).nextUntil("h3","em").show();
});
});
Upvotes: 1
Reputation: 30557
Use nextUntil() like
$(this).nextUntil("h3").show();
This will get all next sibling elements until the provided selector
$(document).ready(function () {
$(".span_1_of_2 h3").click(function () {
$(this).nextUntil("h3").show();
});
});
.span_1_of_2 h3 {
cursor: pointer;
}
.span_1_of_2 em {
display: none;
}
.span_1_of_2 br {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="col span_1_of_2">
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
<h3>Title</h3>
<br/><em>text goes here</em>
<br/>
<br/>
<hr/>
</div>
Upvotes: 2