Home >Web Front-end >JS Tutorial >Detailed explanation of how JavaScript dynamically creates DOM instances using strings
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('2542758666a07fb3434c46053744f671Hello World!94b3e26ee717c64999d7867364b1b4a3');
The purpose of today is to teach you how to implement such a method to directly convert a string into a standard DOM object
start:
In fact, it is very simple to implement such a conversion. Here we mainly use an attribute innerHTML.
innerHTML, I believe everyone has used it, especially to dynamically convert an element It is used when inserting content. Here I will introduce innerHTML for the convenience of those who are not familiar with it.
InnerHTML is not a w3c standard, it was invented and created by IE. However, due to the convenience of this attribute and the status of Weibo at the time, other non-IE browsers also built-in innerHTML and provided support.
Although innerHTML is not a w3c standard, it is a de facto standard. This de facto standard is very important. That is, all mainstream browsers currently support innerHTML, so it is naturally compatible with multiple browsers.
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!