IordanTanev
IordanTanev

Reputation: 6240

Convert string to Dom node javascript?


i have this code

var tmpEl = document.createElement('div')
tmpEl.innerHTML = stringEl;
return tmpEl.firstChild

which i use for converting text to Dom node. The problem is that if stringEl contains <tr> tag i must create table tag not div for this to work.Also if want this code to work with stringEl contaning li tag i must create ol or ul insted of div tag. Is there any generic for converting string to Dom node?
Best Regards,
Iordan

Upvotes: 3

Views: 8531

Answers (2)

Tim Down
Tim Down

Reputation: 324567

There is a method of DOM Range designed for this: createContextualFragment(). It's specified in the DOM Parsing and Serialization spec and is implemented Mozilla, WebKit and Opera browsers (but not IE, yet).

Here's an example: http://jsfiddle.net/gbWCS/

HTML:

<table id="table">
    <tr id="firstRow"><td>One</td><td>Two</td></tr>
</table>

JavaScript:

var html = "<tr><td>Three</td><td>Four</td></tr>";
var table = document.getElementById("table");
var range = document.createRange();
range.selectNodeContents(table);
var frag = range.createContextualFragment(html);
table.appendChild(frag);

Upvotes: 3

user1720624
user1720624

Reputation:

function domNode(nodeType, text) {
var node = document.createElement(nodetype);
node.appendChild(document.createTextNode(text));
return node;
}

domNode('p', 'Hello World!');

Something like that allows you to choose a tag.

Edit: In fact...

function domNode(nodeType, text) {
    var node = document.createElement(nodetype);
    if (text) node.appendChild(document.createTextNode(text));
    return node;
    }

var myList = domNode('ul').appendChild(domNode('li', 'This is a list item!'));

Upvotes: 2

Related Questions