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

134
Views
How to wrap a specific element in a div

Currently, my website has the following structure:

<div class="aa">

  <h2 class="bb">example</h2>

</div>

And I want to create a new div and put h2 inside it.

<div class="aa">

    <div class="cc">  <---

          <h2 class="bb">example</h2>

    </div>  <---

</div>

I tried using insertBefore code as below.

<script>
    const parent = document.querySelector('.bb');
    const billingField1 = document.querySelector('.aa');

    const newDiv = document.createElement('div');
    newDiv.setAttribute('id', 'cc');
    newDiv.style.cssText = 'Hi there';

    parent.insertBefore(newDiv, billingField1);
</script>

With this method, a new div element is inserted only with

<div class="cc"></div> 

I'm wondering if there is any way to put it in.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try this

document.getElementByClassName(‘bb’).innerHTML = ‘<div class=“cc”>’ + document.getElementByClassName(‘bb’).innerHTML + ‘</div>’;
about 4 years ago · Juan Pablo Isaza Report

0

After you insert the new element, you need to make the old element a child of it.

const parent = document.querySelector('.aa');
const billingField1 = document.querySelector('.bb');

const newDiv = document.createElement('div');
newDiv.setAttribute('id', 'cc');
newDiv.style.cssText = 'Hi there';

parent.insertBefore(newDiv, billingField1);
newDiv.appendChild(billingField1);
<div class="aa">
  <h2 class="bb">example</h2>
</div>

You also had the selectors for parent and billingField1 swapped.

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!