Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a DOM object, given its rendered string?

Is there a way to create a DOM object from the whole string, not just the innerHTML? I have a string in the form of a complete rendered DOM:

<some_tag_name class=... id=...>inner text</some_tag_name>     (1)

and want to directly create a DOM object out of it. I know that there is a way to do:

e = document.createElement("some_tag_name")
e.innerHTML = ...
e.className = ...
e.id = ...

but when I do that, I have to extract the innerhtml part from the string (1) that I have, and analyze the tag type and all the attributes and assign that to e separately. I want to do all that simply from the string in the form of (1) that I have.

Edit

I followed the answers, but it was trickier than it seemed at first. The problem is that when you have a string representing things like tr, td, etc., and you try to put that as the innerHTML to a temporarily created div, the browser automatically adds extra tags outside of it. The following is my workaround to overcome this problem, where c is the string and e is the created element:

var cTagName = c.match(new RegExp('[a-zA-Z]+'))[0].toUpperCase();
var e = document.createElement("div");
    e.innerHTML = c;
    e = e.children[0];
//// When the type of `e' does not match what `c' expects, the browser
////    automatically modifies the type of c. The following is to undo this.
if(e.tagName.toUpperCase() != cTagName){
    e = document.createElement("table");
    e.innerHTML = c;
    e = e.children[0];
};
if(e.tagName.toUpperCase() != cTagName){
    e = document.createElement("tbody");
    e.innerHTML = c;
    e = e.children[0];
};
if(e.tagName.toUpperCase() != cTagName){
    e = document.createElement("tr");
    e.innerHTML = c;
    e = e.children[0];
};
like image 623
sawa Avatar asked Feb 22 '23 01:02

sawa


1 Answers

You can always do:

var div = document.createElement("div");
div.innerHTML = "<some> ... </some>"
var e = div.children[0];

(or if you're using jQuery, simply $("<some ... >")[0]).

like image 61
Sophie Alpert Avatar answered Feb 23 '23 16:02

Sophie Alpert