Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a document.createHTMLNode()?

I want to insert html at the current range (a W3C Range).

I guess i have to use the method insertNode. And it works great with text.

Example:

var node = document.createTextNode("some text");
range.insertNode(node);

The problem is that i want to insert html (might be something like "<h1>test</h1>some more text"). And there is no createHTMLNode().

I've tried to use createElement('div'), give it an id, and the html as innerHTML and then trying to replace it with it's nodeValue after inserting it but it gives me DOM Errors.

Is there a way to do this without getting an extra html-element around the html i want to insert?

like image 752
Martin Avatar asked Sep 25 '11 11:09

Martin


2 Answers

Because "<h1>test</h1>some more text" consists of an HTML element and two pieces of text. It isn't a node.

If you want to insert HTML then use innerHTML.

Is there a way to do this without getting an extra html-element around the html i want to insert?

Create an element (don't add it to the document). Set its innerHTML. Then move all its child nodes by looping over foo.childNodes.

like image 113
Quentin Avatar answered Sep 23 '22 06:09

Quentin


In some browsers (notably not any version of IE), Range objects have an originally non-standard createContextualFragment() that may help. It's likely that future versions of browsers such as IE will implement this now that it has been standardized.

Here's an example:

var frag = range.createContextualFragment("<h1>test</h1>some more text");
range.insertNode(frag);
like image 29
Tim Down Avatar answered Sep 24 '22 06:09

Tim Down