To dynamically create a standard dom object in JavaScript, generally use:
var obj = document.createElement('p');
Then set some properties for obj.
However, in actual use, some people may think that it would be great if a standard dom object could be created like this
Pseudo code: var obj=strToDom('
Hello World!
');function parseDom(arg) { var objE = document.createElement("p"); objE.innerHTML = arg; return objE.childNodes; };
The conversion is achieved in just a few lines of code. We first create a p using the standard method, and then use innerHTML to insert an element. In fact, we use the browser's own kernel algorithm to A conversion implemented. Return it using childNodes.
In this way, we have completed the conversion of a string to standard DOM. Cleverly using the browser's own algorithm, we can complete a large number of complex conversions with a simple and small amount of code. We do not need to parse the string, but leave it to The browser does it itself, which is accurate and error-free.
Usage:
var obj=parseDom('<p id="p_1" class="p1">Hello World!</p>'); var obj=parseDom('<p id="p_1" class="p1">Hello World!</p><span>多个也没关系</span>');
Note:
childNodes returns an array-like list. So if it is an element, to use this dom you need to use obj[0] like this. If it is multiple DOM conversions at the same level, you can use obj[0], obj[1]...
The above is the detailed content of Detailed explanation of how JavaScript dynamically creates DOM instances using strings. For more information, please follow other related articles on the PHP Chinese website!