When your application relies on a particular JavaScript class library, you inadvertently try to solve some of the library's own problems, not the language problem. For example, when I try to wrap text (which may also contain HTML elements) with a DIV element. Suppose you have the following HTML:
This is some text and <a href= "" >a link</a>
This time if you want to convert it to the following:
<div>this is some text and <a href= "" >a link</a><div>
The simplest method of violence is that you can perform an update on the parent element by using the. InnerHTML property, but the problem is that all of the bound event listeners will fail because an HTML element is recreated when you use InnerHTML. This is a big glass! So this time can only use JavaScript to achieve--the ruler is short, inch. Here is the implementation code:
var newwrapper = document.createelement (' div ');
while (existingparent.firstchild) {
//move DOM element, does not create new element
Newwrapper.appendchild (existingparent.firstchild);
}
The For loop cannot be used here because ChildNodes is a collection of dynamic nodes, as long as the mobile node affects his index value. We use the while loop to detect the firstchild of the parent element, and if it returns a value that represents false, then you know that all nodes have moved to the new parent!