[jQuery] Applying nextUntil only to h4 containing a link

[jQuery] Applying nextUntil only to h4 containing a link


I'm using nextUntil to apply show/hide content functionality based on
its "section", defined as having an h4 heading. This works great.
Thanks, Richard D. Worth, for pointing me to the nextUntil samples)
$.fn.nextUntil = function(expr) {
var match = [];
if ( expr.jquery )
expr = expr[0];
// We need to figure out which elements to push onto the array
this.each(function(){
// Traverse through the sibling nodes
for( var i = this.nextSibling; i; i = i.nextSibling ) {
// Make sure that we're only dealing with elements
if ( i.nodeType != 1 ) continue;
// If we find a match then we need to stop
if ( expr.nodeType ) {
        if ( i == expr ) break;
} else if ( jQuery.multiFilter( expr, [i] ).length )
break;
// Otherwise, add it on to the stack
match.push( i );
}
});
return this.pushStack( match, arguments );
};
$(document).ready(function(){
    $("#PageTemplateForm h4").each(function(){
    $(this).nextUntil("h4, h3").wrap("<div class='expand'></div>");
    $(".expand").hide();
    $(".closed").click(function(event){
        $(this).parent().next().toggle();
        $(this).toggleClass("open");
        return false;
        });
    })
I now find I have some h4s that will not have toggling links and
should not have this toggling functionality applied. The rule would
be that an h4 that contains a link should have its following content
wrapped (up to the next h3 or h4) and hidden. An h4 that does not
contain a link should be skipped. I tried:
$("#PageTemplateForm h4 a").each(function(){
I can see why that wouldn't work, because the "expand" div would would
likely be inserted in the wrong place. How would I distinguish
between h4s followed by links vs h4s not followed by links? Thanks in
advance!
jp