Currently, my website has the following structure:
<div >
<h2 >example</h2>
</div>
And I want to create a new div and put h2 inside it.
<div >
<div > <---
<h2 >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 ></div>
I'm wondering if there is any way to put it in.
CodePudding user response:
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 >
<h2 >example</h2>
</div>
You also had the selectors for parent
and billingField1
swapped.
CodePudding user response:
Try this
document.getElementByClassName(‘bb’).innerHTML = ‘<div class=“cc”>’ document.getElementByClassName(‘bb’).innerHTML ‘</div>’;