1

I'm using appendChild to insert an iframe between paragraphs dynamically. The problem is that (for some reason) the iframe is being inserted BEFORE the </p> and not AFTER, as I need.

My original HTML:

<p>Some text</p>
<p>Some text</p>
<p>Some text</p>
<p>Some text</p>

My JavaScript:

var elements = document.getElementsByTagName('p'); // array of paragraphs
var ifrm = document.createElement("iframe"); // create iframe
ifrm.setAttribute("src", "https://example.com"); // set iframe URL
elements[2].appendChild(ifrm); // insert iframe 

What I get:

<p>Some text</p>
<p>Some text</p>
<p>Some text <iframe src="..."></iframe> </p>
<p>Some text</p>

What I expect to get:

<p>Some text</p>
<p>Some text</p>
<p>Some text</p> <iframe src="..."></iframe>
<p>Some text</p>

What I'm doing wrong?

Christian
  • 13
  • 2
  • You cannot have a block-level element like ` – Pointy Apr 30 '21 at 20:54
  • 1
    Here you go: https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib. You need to insert it AFTER the

    , (so it becomes a sibling, not a child)

    – V Maharajh Apr 30 '21 at 20:55

1 Answers1

0

elements[2].parentNode.insertBefore(ifrm, elements[3])

var elements = document.getElementsByTagName('p'); // array of paragraphs
var ifrm = document.createElement("iframe"); // create iframe
ifrm.setAttribute("src", "https://example.com"); // set iframe URL
elements[2].parentNode.insertBefore(ifrm, elements[3]);
<p>Some text</p>
<p>Some text</p>
<p>Some text</p>
<p>Some text</p>
Spectric
  • 30,714
  • 6
  • 20
  • 43