I need to check if any fieldset in the DOM is empty. Empty means that it has not text inside (legend is not inside). For example, this is an empty fieldset:
<fieldset>
<legend>a1</legend>
<input type="hidden" name="x" value="y">
</fieldset>
It has no text nodes except inside legend.
Until now I was using this JQuery to check this condition:
if ($(this).find(":not(legend)").text().trim() == '') {
...
}
Note this comes from a .each() call. The problem is that now I’ve found that it doesn’t works on nested fieldsets like this:
<fieldset>
<legend>a</legend>
<fieldset>
<legend>a1</legend>
</fieldset>
<fieldset>
<legend>a2</legend>
</fieldset>
</fieldset>
In this case the jquery expression:
$("fieldset").find(":not(legend)").text().trim()
returns “a1 a2” as a result. What’s the problem? JsFiddle
you need to take into account fieldsets which have fieldsets. What is happening is the selector is saying “this fieldset has a fieldset and since you are looking for anything that is not a legend this is a valid element”. It then finds the text in that element which is the a1 and the a2
Update:
per your comment below, try this solution.