Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
Obtenga todos los elementos entre el tipo de elemento (h1) y envuélvalos en div

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>" );
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  1. Debe usar .each jQuery API para lograrlo.
 $("h1").each(function(){})
  1. .prevUntil el recorrido del nodo Dom, use .nextUntil en su lugar.

  2. 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>
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!