user3499262
user3499262

Reputation: 39

Alternative to document.write javascript?

I had a working alternative I think.... I believe I erased it now I can not find it. Does anybody know an alternative to document.write javascript? Here is the code:

document.write('<div id="myDiv1"></div>');

Does anybody know an alternative to document.write javascript?

Upvotes: 0

Views: 991

Answers (2)

Brett Zamir
Brett Zamir

Reputation: 14345

The document.create<...> solution is the safest, but if you need to insert raw HTML stored as a string (from a trusted source only, e.g., do not use this method with content posted by other users, even if modern browsers are disallowing), you can use innerHTML or outerHTML:

document.body.innerHTML += '<b>I can add raw markup!<\/b><img src="x" onerror=\'alert("But be careful!")\'>';

See https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML to understand more on the ongoing risks of using innerHTML or outerHTML with untrusted content. It is basically as dangerous as using eval() with untrusted content.

Upvotes: 0

Thomas Junk
Thomas Junk

Reputation: 5676

What about document.create<...>?

 var newDiv = document.createElement("div"); 
 var newContent = document.createTextNode("Whateveryourcontentis");
 newDiv.appendChild(newContent);
 document.querySelector("#mytarget").appendChild(newDiv)

Alternatively if you have to enter a more complex structure I would use DocumentFragment

Upvotes: 1

Related Questions