Andy
Andy

Reputation: 11492

jQuery - select all text "underneath" a h1 or h2

Say I have a document with a mixture of <h1>, <h2> <h3> etc, plus other elements like <p>.

from the DOM perspective, each element is sat directly under the <body>, but obviously from a semantic perspective, the elements are nested by heading level

I'm trying to implement some kind of slideUp/slideDown outline expander so when the user clicks an h2, for example, I need to search down the document until I find another heading of level h2 or better, and then collect all the elements in between as being the content which is semantically "under" that h2.

at the moment, I'm assuming I'll just have to wrap it all in nested divs to make the DOM tree nesting match the semantics, but is there any way to avoid that?

Upvotes: 1

Views: 998

Answers (2)

dreamweiver
dreamweiver

Reputation: 6002

you dont need to use any divs to wrap the elements, just use .nextUntil(...) like this

Jquery Code:

$('h2').on('click',function (){
       var dom=$(this).nextUntil('h2');
       if($(dom).is(":hidden")){
            $(dom).show(); 
       }
       else{
            $(dom).hide(); 
       }           
});

Ref:http://api.jquery.com/nextuntil/

Live Demo

http://jsfiddle.net/dreamweiver/vag2r/3/

Happy Coding :)

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

You can use nextUntil() for that

$("h2").click(function(){
  $(this).nextUntil("h2")
});

Demo

Upvotes: 2

Related Questions