Reputation: 772
I'm binding the following function to a toggle button I have created to hide/unhide content that is located bellow the button, but on an other level in the DOM.
var togglelabel = packagehead.append("<div>").children().last().addClass("togglewrap").append("<label>")
.children().last().addClass("toggle android header-toggle")
.on('click', function(){
$(this).parent().parent().next('.hidable').toggle();
});
The html structure looks like this:
<div>
<div class="packageheader">
<span>Package #1501</span>
<div class="togglewrap">
<label class="toggle android header-toggle">
<input type="checkbox">
<p>
<span>More</span>
<span>Less</span>
</p>
<a class="slide-button">
</a>
</label>
</div>
</div>
<br>
<p class="hidable">
<pre>content here</pre>
</p>
</div>
This code doesn't work to hide the <p>
with the class .hidable
.
I've tried 'debugging' the code using console.log() to see what element 'this' represents and found that it does, as expected, represent the label element.
So I thought that using the following chain:
$(this).parent().parent().next('.hidable').toggle();
Would correctly go 2 levels up to the <div class="packageheader">
and then take the next sibling with the class hidable, which would be <p class="hidable">
Here is a screenshot of the structure, to be sure I didn't miss anything:
Upvotes: 3
Views: 137
Reputation: 382170
You can do this :
$(this).closest('.packageheader').nextAll('.hidable').first().toggle();
Note that it's slightly preferable to use closest
instead of parent().parent()
as it won't break as easily when the HTML changes and it's easier for the maintainer to decipher what the code does.
Note also that your HTML is invalid, you can't have a PRE
inside a P
.
Upvotes: 4