1

I am trying to use native javascript to append a string of html to a target div. This works fine using:

var selector = document.getElementById('divid');
var str = '<div><h1>string of html content</h1></div>';
selector.innterHTML += str;

Except whenever the document contains an iframe it seems to hide the frame when appending the innerhtml. I tried a work around as follows:

var selector = document.getElementById('divid');
var str = '<div><h1>string of html content</h1></div>';
var div = document.createElement('div');
div.innerHTML = str;
selector.appendChild(div);

This works but now I am creating an unnecessary div container, is there a way to do this without creating a new element that won't erase the iframe?

user1572796
  • 1,057
  • 2
  • 21
  • 46

2 Answers2

3

Except whenever the document contains an iframe it seems to hide the frame when appending the innerhtml

See "innerHTML += ..." vs "appendChild(txtNode)" for the reason - modifying innerHTML creates a new iframe that reloads. Also have a look at What is better, appending new elements via DOM functions, or appending strings with HTML tags?

This works but now I am creating an unnecessary div container

Just don't create an extra div, you have one in your HTML anyway:

var selector = document.getElementById('divid');
var div = selector.appendChild(document.createElement('div'));
div.innerHTML = '<h1>string of html content</h1>';

is there a way to do this without creating a new element that won't erase the iframe?

You can also use the native insertAdjacentHTML method which is the equivalent to jQuery's append with a HTML string:

var selector = document.getElementById('divid');
selector.insertAdjacentHTML('beforeend', '<div><h1>string of html content</h1></div>');
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

This seems to work.

var parser = new DOMParser();
var el = parser.parseFromString(str, "text/html");
selector.appendChild(el.childNodes[0]);
Unihedron
  • 10,902
  • 13
  • 62
  • 72
user1572796
  • 1,057
  • 2
  • 21
  • 46