开发者

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开发者_如何学Go 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?


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.


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);


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


Instead of innerHTML just use appendChild(element); this may help you. If you want comment here, and I will give you an example.


The Range.insertNode() method inserts a node at the start 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜