0

Given a string like that:

<img src="image.png" /><p>some text</p>

How can I append it to a dom node without using jQuery?

I can create something like that:

  var string = '<img src="image.png" /><p>some text</p>';
  var div = document.createElement('div');
  div.innerHTML = string;

and then append it to a node using appendChild, but how can I add only the original string without the wrapping div?

Something like jquery's parseHTML, I need something that parses a string and return it as html nodes.

1 Answer 1

6

You can use insertAdjacentHTML() for this task.

EDIT

If you need to parse a string to elements, you can do something like this:

function parseElements(str) {
    var temp = document.createElement('div'),
        nodes, n,
        elements = [];
    temp.innerHTML = str;
    nodes = temp.childNodes;
    for (n = 0; n < nodes.length; n++) {
        elements.push(nodes[n]);
    }
    return elements;
}
Sign up to request clarification or add additional context in comments.

3 Comments

sorry I didn't explained it too well, I'd like to have something that return html nodes, something like jquery's parseHTML
Well, jQuery seems to create a documentFragment and elements (from the string) into it, then it merges the results to a resulting jQuery object.
and how do they put elements from the string into the fragment? they takes div's child nodes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.