Matteo Pagliazzi
Matteo Pagliazzi

Reputation: 5270

Javascript: string to HTML

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.

Upvotes: 0

Views: 136

Answers (1)

Teemu
Teemu

Reputation: 23416

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

Upvotes: 6

Related Questions