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 innerHTML? I have a line in the form of a full DOM rendering:

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

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

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

but when I do this, I need to extract the innerhtml part from the string (1) that I have, and parse the tag type and all attributes and assign it e separately. I want to do all this simply from a line in form (1), which I have.

Edit

I followed the answers, but it was harder than it seemed at first. The problem is that when you have a line representing things like tr , td , etc., and you try to put this as innerhtml in a temporary div creation, the browser automatically adds extra tags outside of This. Below is my workaround to solve 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]; }; 
+4
source share
3 answers

You can always do:

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

(or if you are using jQuery, just $("<some ... >")[0] ).

+4
source

You are looking for the outerHTML property.

 var el = document.createElement('tag'); document.body.appendChild(el); // The element must be appended to the DOM before // setting outerHTML. Otherwise, it will throw a // NO_MODIFICATION_ALLOWED_ERR. el.outerHTML='<some_tag_name class=... id=...>inner text</some_tag_name>'; 

Given that Firefox is a little behind the times on this, it is probably safer to just create a wrapper div and set its innerHTML .

 var el = document.createElement('div'); el.innerHTML = '<some_tag_name class=... id=...>inner text</some_tag_name>'; 
+4
source

You can do this with jQuery :

 var myDiv = $('<div class="my-div">This is my div!</div>'); 
0
source

Source: https://habr.com/ru/post/1403125/


All Articles