Adding Div With IFrame Through JavaScript

Viewed 51

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

Where to add

<div class="Replace">
  <div class="hello">Hello</div>
  <div class="hi">Hi</div>
  <div class="yes">Wait</div>
</div>

Expected Output

<div class="Replace">
  <div class="hello">Hello</div>
  <div class="hi">Hi</div>
  <div class="yes">Wait</div>
  <div class="newProductPanelContainer">
    <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>
3 Answers

#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.

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);


getElementsByClassName returns a collection. You can iterate over 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 class="Replace">
  <div class="hello">Hello</div>
  <div class="hi">Hi</div>
  <div class="yes">Wait</div>
</div>

Related