Foreword: To dynamically create a standard dom object in JavaScript, generally use:
var obj = document.createElement('div');
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 in this way
Pseudo code: var obj=strToDom('
Hello World!
');
Then 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 change 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.
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 create a div using the standard method, and then use innerHTML to insert an element. In fact, it is a conversion implemented using the browser's own kernel algorithm. 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.
Use:
var obj=parseDom('< ;div id="div_1" class="div1">Hello World!
');
var obj=parseDom('
Hello World!
It doesn’t matter if you have more than one');
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] like this...
That’s it. Here I recommend a js I wrote myself. Framework, the above method is integrated into the framework