2013-05-08 6 views
1

HTML extrait:Comment est-ce que je peux emballer la section implicite dans HTML 5 par jQuery?

<h1>Heading</h1> 
<p>paragraph paragraph paragraph</p> 
<h2>Heading</h2> 
<p>paragraph paragraph paragraph</p> 

L'extrait ci-dessus est égal à:

<section> 
    <h1>Heading</h1> 
    <p>paragraph paragraph paragraph</p> 
    <section> 
    <h2>Heading</h2> 
    <p>paragraph paragraph paragraph</p> 
    </section> 
</section> 

Comme mentionné here.

Maintenant, je veux faire cela par jQuery à partir du premier extrait. Y a-t-il déjà une API pour cela?

Répondre

3

Démo: http://jsfiddle.net/abdennour/LX2YX/

$('h2').next('p').andSelf().wrapAll('<section />'); 

$('h1').next().andSelf().next().andSelf().wrapAll('<section />'); 

Vous pouvez voir l'inspecteur du navigateur pour vérifier votre arbre DOM:

enter image description here

+0

Vous êtes les bienvenus! –

1

Une autre approche qui est facile:

$('h1,p,h2').wrapAll('<section />'); 
$('h2,p:eq(1)').wrapAll('<section />'); 

Demo: http://jsfiddle.net/abdennour/LX2YX/1/

REMARQUE: le sélecteur 'p:eq(1)' signifie la deuxième <p> dans votre page

Questions connexes