JS string to DOM and Dom to string
Objective:
Creating standard DOM objects dynamically in JavaScript is generally used:
var obj = document.createelement (' div ');
Then set some properties for obj.
However, in practice, some people might think that it would be nice to create a standard DOM object like this.
Pseudo code: Var obj=strtodom (' <div id= "div_1" class= "Div1" >hello world!</div> ');
So today's goal is to teach you how to implement a method to convert a string directly to a standard DOM object.
Start
In fact, the implementation of such a conversion is very simple, here is mainly the use of an attribute innerHTML.
InnerHTML, I believe that we have used, especially dynamic into an element inside the content of the use, here I still introduce the next InnerHTML, convenient for people who are not quite familiar with.
innerHTML is not a standard, is invented by IE, but because of the convenience of this property, and then the status of the micro-boss, other non-IE browser has built-in innerhtml and support.
Although innerHTML is not a standard, but it is a fact standard, the fact that the standard is very important, that is, the mainstream browser support innerHTML, naturally do a compatible multi-browser.
Code
function Parsedom (ARG) {
var obje = document.createelement ("div");
obje.innerhtml = arg;
return obje.childnodes;
};
Just a few lines of code to achieve the conversion, we first use the standard method to create a div, in the use of innerHTML to insert an element, in fact, the use of the browser's own kernel algorithm to achieve a transformation. is returned with ChildNodes.
So we completed a string to the standard DOM conversion, clever use of the browser itself algorithm, can use a small amount of code to complete a large number of complex transformations, we do not have to parse the string, but to the browser itself to complete, this is both accurate and error-free.
Use:
var obj=parsedom (' <div id= ' div_1 "class=" Div1 ">hello world!</div> ');
var obj=parsedom (' <div id= ' div_1 "class=" Div1 ">hello world!</div><span> multiple also does not matter </span> ');
Attention:
ChildNodes returns an array-like list. So if this is an element, use this DOM to use obj[0]. If the DOM conversion is multiple siblings, you can use obj[0], obj[1] ...
Dom-to-string is simpler and can be implemented using a three-party class library
The method provided in jquery with Dom-to-string is var domstr= $ ("#"). html ();
Conversion principle you can refer to the source code, it should be used in a deep traversal of the way to return the stitching string
End
Here is the end, here to recommend a I write my own JS framework, the above method is integrated in the framework
Use: B$.parsedom (' <div id= "div_1" class= "Div1" >hello world!</div> ')
Transferred from: http://zha-zi.iteye.com/blog/1931474
JS string to DOM and Dom to string