Tengo la siguiente estructura:
<div class="wrapper"> <h1>Header 1</h1> <h2>subtitle 1</h2> <p>aaa</p> <p>bbb</p> <p>ccc</p> <h2>subtitle2</h2> <p>ddd</p> <h1>Header 2</h1> <h2>subtitle 3</h2> <p>eee</p> <p>fff</p> </div>Quiero seleccionar todos los elementos h1 y p entre cada h1 y envolverlos en un div, así que termino con:
<div class="wrapper"> <div> <h1>Header 1</h1> <h2>subtitle 1</h2> <p>aaa</p> <p>bbb</p> <p>ccc</p> <h2>subtitle2</h2> <p>ddd</p> </div> <div> <h1>Header 2</h1> <h2>subtitle 3</h2> <p>eee</p> <p>fff</p> </div> </div>He intentado varias cosas como las siguientes, pero ninguna funciona perfectamente:
$( "h1" ).prevUntil( "h1" ).wrapAll( "<div></div>" ); $("h1").each(function(){}) .prevUntil el recorrido del nodo Dom, use .nextUntil en su lugar.
para que coincida con la salida final, el script es el siguiente:
<script> $("h1").each(function() { $(this).nextUntil( "h1" ).wrapAll( "<div></div>" ); // uncomment the two lines to move the h1 inside the wrapped div // const el = $(this).next(); // $(this).prependTo(el); }); </script>Se me ocurrió esta solución donde obtiene a todos los niños y luego, si es una etiqueta h1, creará un nuevo div y moverá H1 y otros niños a él.
var newDiv; $(document).ready(function(){ $(".wrapper").children().each(function(){ if($(this).is("h1")){ $(this).before("<div></div>"); newDiv = $(this).prev(); newDiv.append($(this)); }else{ newDiv.append($(this)); } }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <h1>Header 1</h1> <h2>subtitle 1</h2> <p>aaa</p> <p>bbb</p> <p>ccc</p> <h2>subtitle2</h2> <p>ddd</p> <h1>Header 2</h1> <h2>subtitle 3</h2> <p>eee</p> <p>fff</p> </div>