I run wordpress website and I want to add the following elements between specific elements using JavaScript.
<div id="wrap" style="display:none;border:1px solid;width:500px;height:300px;margin:5px 0;position:relative"></div>
However, no matter how many hours I look at numerous examples on the internet and follow along, the div element is not added...
Website structure is
<div >
<p >..
<span >...
</span>
</p>
<div id="wrap" ..> </div> <- want to put div here
<p >
<span >
And
i tried below codes.
document.body.onload = addElement;
function addElement () {
var newDiv = document.createElement("div");
var currentDiv = document.getElementById("warp");
document.billing_address_1_field.insertBefore(newDiv, currentDiv);
}
or
<script>
let newDiv = document.createElement("div");
newDiv.setAttribute("id", "wrap");
let par = document.getElementsByClassName("billing_postcode_find_field")[0];
par.appendChild(newDiv);
</script>
Could someone please let me know what am I missing?
Website link is [here][1]
Thank you. [1]: https://seoartgallery.com/test5/?page_id=15/?add-to-cart=34&quantity[1]
CodePudding user response:
It looks like you're just trying to add this new element as the first child of the .woocommerce-input-wrapper
element. In this case, you can use prepend()
<div >
<p >
<span >
<p >
<span >this is the span in p tag</span>
</p>
</span>
</p>
</div>
<script>
const parent = document.querySelector('.woocommerce-input-wrapper');
const newDiv = document.createElement('div');
newDiv.setAttribute('id', 'wrap');
newDiv.innerText = `I'm new!`;
parent.prepend(newDiv);
</script>
If there were to be an element above the .billing_address_1_field
element, then you could use .insertBefore()
instead to ensure that it would go in between the elements you want it to:
<div >
<p >
<span >
<p>i'm a random p tag at the top of the container</p>
<p >
<span >this is the span in p tag</span>
</p>
</span>
</p>
</div>
<script>
const parent = document.querySelector('.woocommerce-billing-fields__field-wrapper');
const billingField1 = document.querySelector('.billing_address_1_field');
const newDiv = document.createElement('div');
newDiv.setAttribute('id', 'wrap');
newDiv.innerText = `I'm new!`;
parent.insertBefore(newDiv, billingField1);
</script>