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.
Try this
document.getElementByClassName(‘bb’).innerHTML = ‘<div class=“cc”>’ + document.getElementByClassName(‘bb’).innerHTML + ‘</div>’;
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.