When your application relies on a specific JavaScript library, you are inadvertently trying to solve problems with the library itself, rather than with the language. Like 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>
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 simplest brute force method is that you can perform updates through the .innerHTML property on the parent element, but the problem is that all bound event listeners will be invalid because using innerHTML will recreate an HTML element. What a big glass! So at this time, we can only use JavaScript to achieve it - the ruler is short and the inch is long. The following is the implementation code:
var newWrapper = document.createElement('div'); while(existingParent.firstChild) { // 移动DOM元素,不会创建新元素 newWrapper.appendChild(existingParent.firstChild); }
For loop cannot be used here, because childNodes is a collection of dynamic nodes, and moving a node will affect its index value. We use a while loop to keep checking 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!