When your application needs to rely on a specific JavaScript class library, you will inadvertently try to solve the problems of some class library itself, rather than language problems. For example, when I try to wrap the text (which may also contain HTML elements) with a DIV element. Suppose there is the following HTML:
This is some text and <a href="">a link</a>
At this time, if you want to convert it to the following:
<div>This is some text and <a href="">a link</a><div>
The easiest way to brute force is that you can perform updates on the parent element via the .innerHTML property, but the problem is that all bound event listening will be invalid because an HTML element will be recreated when using innerHTML. This is such a big glass! So at this time, you can only use JavaScript to achieve it - there is a shortcoming and a shortcoming. Here is the implementation code:
var newWrapper = document.createElement('div'); while(existingParent.firstChild) { // Move the DOM element, newWrapper.appendChild(existingParent.firstChild); }You cannot use a for loop here because childNodes is a collection of dynamic nodes, and as long as you move the node, it will affect its index index value. We use a while loop to detect the firstChild of the parent element. If it returns a value representing false, then you know that all nodes have been moved to the new parent!