I'm trying to achieve a toggle effect on a website. The html looks like this:
<div class="prod-toggle-click">
<h2>Test</h2>
<div class="prod-toggle">
<p>test</p>
</div>
</div>
<div class="prod-toggle-click">
<h2>Test 2</h2>
<div class="prod-toggle">
<p>test 2</p>
</div>
</div>
And the JS:
<script>
$(".prod-toggle-click").click(function(){
$(this).parent().find('.prod-toggle').toggle();
});
</script>
This toggles the .prod-toggle
of both divs. But I only need the .prod-toggle
of the parent to toggle.
I've tried it like this:
<script>
$(".prod-toggle-click").click(function(){
$(this).next('.prod-toggle').slideToggle();
});
</script>
but that's not working either. Any suggestions?
You just need to use find('.prod-toggle')
and remove the parent()
or next()
which you are using. This is because the div
with class prod-toggle
is inside the div
with class prod-toggle-click
so find()
will simply work for you here.
$(".prod-toggle-click").click(function(){ $(this).find('.prod-toggle').toggle(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="prod-toggle-click"> <h2>Test</h2> <div class="prod-toggle"> <p>test</p> </div> </div> <div class="prod-toggle-click"> <h2>Test 2</h2> <div class="prod-toggle"> <p>test 2</p> </div> </div>
You need put this under $(document).ready and also remove parent()
$(document).ready(function () {
$(".prod-toggle-click").click(function(){
$(this).find('.prod-toggle').toggle();
});
});
For this specific case, I would use children()
instead of find()
. It only looks at the immediate children of the node. It is more explicit and that's the reason of my preference. I guess performance is not an issue but children()
should also be faster.
$(".prod-toggle-click").click(function(){
$(this).children(".prod-toggle").toggle();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.