I’m using jQuery to show and hide elements upon user interaction. The following code works fine:
<script type="text/javascript">
$(document).ready(function () {
$('.c').hide();
$('.b').click(function() {
var t = $(this);
t.parent().find('.c').show();
});
});
</script>
<div class="a">
<a href="#" class="b">Show</a>
<div class="c">This is hidden text</div>
</div>
But when i put the link inside a div tag the code does not work. I couldn’t figure out the problem. So I’m expecting some help.
<script type="text/javascript">
$(document).ready(function () {
$('.c').hide();
$('.b').click(function() {
var t = $(this);
t.parent().find('.c').show();
});
});
</script>
<div class="a">
<div class="d"><a href="#" class="b">Show</a></div> //if i place it inside div it doesn't work
<div class="c">This is hidden text</div>
</div>
Can anyone point out why it’s not working??
As the containing div is no longer the parent of the link, it doesn’t work to use
.parent()to find it. Use.closest('.a')to find it:This will work to find the element with class
cin the same containing element, regarldess of what elements you put in there.