The purpose of today is to teach you how to implement such a method to convert strings directly into standard dom objects.
Preface:
It is generally used to dynamically create standard dom objects in javascript:
Var obj = document. createElement ('P ');
Then set some properties for obj.
However, in actual use, some people may think that it would be nice to create a standard dom object like this.
Pseudocode: var obj = strToDom ('
Hello World!
');
The purpose of today is to teach you how to implement such a method to convert strings directly into standard dom objects.
Start:
In fact, implementing such a conversion is very simple. Here we mainly use an attribute innerHTML.
InnerHTML, I believe everyone has used it, especially when dynamically inserting content into an element. Here I am still introducing innerHTML, which is convenient for people who are not familiar with it.
InnerHTML is not a w3c standard and was invented by ie. However, due to the convenience of this attribute and the position of micro-boss at that time, other non-ie browsers also built innerHTML and provided support.
Although innerHTML is not a w3c standard, it is a fact standard. This fact standard is very important, that is, the mainstream browsers currently support innerHTML. Naturally, it is compatible with multiple browsers.
Code:
The Code is as follows:
Function parseDom (arg ){
Var objE = document. createElement ("p ");
ObjE. innerHTML = arg;
Return objE. childNodes;
};
Just a few lines of code implement the conversion. We first create a p using the standard method and insert an element with innerHTML, in fact, it is a conversion implemented by using the browser's own kernel algorithm. Return with childNodes.
In this way, we have completed the conversion from a string to a standard dom, cleverly using the browser's own algorithm, you can use a small amount of code to complete a large number of complex conversions, we do not need to parse the string, it is done by the browser, which is both accurate and correct.
Usage:
The Code is as follows:
Var obj = parseDom ('
Hello World!
');
Var obj = parseDom ('
Hello World!
It doesn't matter if there are multiple ');
Note:
ChildNodes returns a list similar to an array. So if it is an element, to use this dom, you need to use obj [0] in this way. For dom conversion at multiple levels, you can use obj [0], obj [1]…
End
This is the end. Here we recommend a self-written js framework. The above method is integrated into the framework.
Use: B $. parseDom ('
Hello World!
')
BBank open-source Javascript framework