Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an HTML string to a DocumentFragment?

I'm adding textnodes to a documentFragment like this:

var foo = document.createDocumentFragment();
var someText = "Hello World";
foo.appendChild(document.createTextNode(someText));

This works fine, but sometimes I'm being passed "text" which includes inline links like this:

var someOtherText = "Hello <a href='www.world.com'>World</a>";

Which in my handler is converted to hardcoded text instead of a link.

Question:
How do I append an HTML string like the above into a documentFragment? If I'm not using textNodes can this be done using appendChild?

like image 204
frequent Avatar asked Nov 12 '13 12:11

frequent


People also ask

How do you append text in HTML?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')

How do you add a string to a DOM in HTML?

#Using insertAdjacentHTML() The method works by parsing the specified string as HTML (or XML) and inserts it into the DOM tree at the specified position. It has the following signature: element. insertAdjacentHTML(position, text);

How do you use an HTML fragment?

To create a new HTML Fragment:Paste your HTML code into the large HTML Code box. Choose between the 'Manual', 'Head' and 'Body' types. Click the Add HTML Fragment button. You will be returned to the HTML Fragments screen where your new fragment will now be listed.


2 Answers

Creates a temporary div, inserts the text in innerHTML, and then moves all nodes of the div to the fragment. Since an element only can be in one place at a time, it will automatically be removed from the temporary div-tag.

var frag = document.createDocumentFragment();

var div = document.createElement('div');
div.innerHTML = '<a href="http://stackoverflow.com/">Stack overflow</a>';
while (div.firstChild) frag.appendChild(div.firstChild);
like image 69
some Avatar answered Oct 27 '22 11:10

some


document.createRange().createContextualFragment("<span>Hello World!</span>");

It returns a DocumentFragment.

Support IE >= 9

EDIT:

recent versions Safari seems to fail with the short way, here is a little bit longer but working way:

var range = document.createRange();
range.selectNode(document.body); // Select the body cause there is always one (documentElement fail...)

var fragment = range.createContextualFragment("<span>Hello World!</span>");
like image 41
Jordan Avatar answered Oct 27 '22 09:10

Jordan