Why is there no document.createHTMLNode () document?

I want to insert html in the current range (W3C range).

I think I need to use the insertNode method. 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 (maybe something like "<h1> test </ h1> some text"). And no createHTMLNode ().

I tried using createElement ('div'), giving it id and html as innerHTML, and then trying to replace it with nodeValue after inserting it, but it gives me DOM errors.

Is there a way to do this without getting the extra html element around the html that I want to insert?

+9
source share
5 answers

Because "<h1>test</h1>some more text" consists of an HTML element and two parts of text. This is not a node.

If you want to embed HTML, use innerHTML .

Is there a way to do this without getting the extra html element around the html that I want to insert?

Create an element (do not add it to the document). Install it innerHTML. Then move all of its child nodes by going through foo.childNodes .

+9
source

In some browsers (in particular, not in any version of IE) Range objects have initially non-standard createContextualFragment() , which can help, Probably, future versions of browsers, such as IE, will implement this now, when it was standardized .

Here is an example:

 var frag = range.createContextualFragment("<h1>test</h1>some more text"); range.insertNode(frag); 
+4
source

Instead of innerHTML just use appendChild (element); it can help you. If you want to comment here, I will give you an example.

+3
source

Try

 function createHTMLNode(htmlCode, tooltip) { // create html node var htmlNode = document.createElement('span'); htmlNode.innerHTML = htmlCode htmlNode.className = 'treehtml'; htmlNode.setAttribute('title', tooltip); return htmlNode; } 

From: http://www.koders.com/javascript/fid21CDC3EB9772B0A50EA149866133F0269A1D37FA.aspx

+2
source

The Range.insertNode () method inserts a node at the beginning of the range.

 var range = window.getSelection().getRangeAt(0); var node = document.createElement('b'); node.innerHTML = 'bold text'; range.insertNode(node); 

Resources

https://developer.mozilla.org/en-US/docs/Web/API/range/insertNode

0
source

All Articles