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]; };
source share