I have a jQuery function which toggles the visibility of the contents of a fieldset when its legend is clicked, leaving just the fieldset border (if there is one) and the legend showing:
$('legend.togvis').click(function() {
$(this).siblings().toggle();
return false;
});
It works great unless the fieldset contains text nodes.
<fieldset><legend class='togvis'>Click Me</legend>
<p>I toggle when the legend is clicked.</p>
But I'm a recalcitrant text node and refuse to toggle.
</fieldset>
In an effort to toggle the text nodes too I tried this:
$('legend.togvis').click(function() {
$(this).parent().contents().not('legend').toggle();
return false;
});
which works the same as the first function. And this:
$('legend.togvis').click(function() {
$(this).parent().contents(":not(legend)").toggle();
return false;
});
which throws the error
Message: 'style.display' is null or not an object
Line: 5557
Char: 3
Code: 0
URI: http://code.jquery.com/jquery-1.4.4.js
Any thoughts on how to get the entire contents of a fieldset (minus the legend) to toggle when the legend is clicked?
ETA Solution, with many thanks to Eibx
$('legend.togvis').click(function() {
$(this).parent().contents().filter(
function() { return this.nodeType == 3; }).wrap('<span></span>');//wrap any stray text nodes
$(this).siblings().toggle();
});