The JavaScript implementation USES a DIV to wrap the text element node

  • 2020-03-30 03:53:04
  • OfStack

When your application needs to rely on a particular JavaScript library, you'll inadvertently try to solve some library's own problems, not the language's. For example, when I try to wrap the text (which may also contain HTML elements) in a DIV element. Assume the following HTML:


This is some text and <a href="">a link</a>

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 do this is to do an update with the.innerhtml attribute on the parent element, but the problem is that all of the bound event listeners will be disabled, because using innerHTML recreates an HTML element. What a big glass! So this is the only way to use JavaScript to achieve -- the short, the good. The following is the implementation code:


var newWrapper = document.createElement('div'); 
while(existingParent.firstChild) { 
//Moving a DOM element does not create a new element
newWrapper.appendChild(existingParent.firstChild); 
}

The for loop cannot be used here because childNodes is a collection of dynamic nodes, and any move of the node will affect its index value. We use the while loop to always detect the parent's firstChild, and if it returns a value representing false, then you know that all the nodes have moved to the new parent!


Related articles: