Home > Back-end >  Adding Div With IFrame Through JavaScript
Adding Div With IFrame Through JavaScript

Time:09-19

I need to newProductPanelContainer insie replace through JS. I'm wondering why this doesn't add anything? I'm adding an iframe to it.

Where to add

<div >
  <div >Hello</div>
  <div >Hi</div>
  <div >Wait</div>
</div>

Expected Output

<div >
  <div >Hello</div>
  <div >Hi</div>
  <div >Wait</div>
  <div >
    <iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>
  </div>
</div>

Iframe div

<script type="text/javascript">
  var innerDiv = document.createElement("div");
  innerDiv.className = 'newProductPanelContainer';
  innerDiv.innerHTML = `<iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>`;
  innerDiv.style.width = "100%";
    var hello = document.getElementsByClassName("Replace");
hello.appendChild(innerDiv);

</script>

CodePudding user response:

#1: You can not create an element with specific class name newProductPanelContainer with just document.createElement("newProductPanelContainer")

you can use the 2nd parameter to do that (the options) refer this

#2: You can not get the DOM of un-mount element const productPanelIFrame = document.getElementById("productPanelIFrame");

the Iframe.productPanelIFrame is the children of div.newProductPanelContainer. But you can see, its parent has not mounted yet.

CodePudding user response:

Try this. It works for me

const innerDiv = document.createElement("div");
innerDiv.className = "newProductPanelContainer";
innerDiv.style.width = "100%";
const iFR = document.createElement("iframe");
iFR.id = "productPanelIFrame";
iFR.src = "https://test.com";
iFR.width = "100%";
iFR.height = "100%";
iFR.style = "border: none";

const hello = document.getElementsByClassName("Replace");
hello[0].appendChild(innerDiv);
innerDiv.appendChild(iFR);


CodePudding user response:

getElementsByClassName returns a collection. You can itterate the collection and add the iframe to each element in the collection or select an (probably the first) element and add the iframe to that.

Alternatively use the querySelector method which returns the first matching element in the DOM. This is what I have done below. Note don't get confused with querySelectorAll, which returns a collection.

var innerDiv = document.createElement("div");
  innerDiv.className = 'newProductPanelContainer';
  innerDiv.innerHTML = `<p>I'm inserted</p><iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>`;
  innerDiv.style.width = "100%";
    var hello = document.querySelector(".Replace");
hello.appendChild(innerDiv);
<div >
  <div >Hello</div>
  <div >Hi</div>
  <div >Wait</div>
</div>

  • Related