When I try to wrap the text (which may also contain HTML elements) with a DIV element, we can use the following method, if your application depends on a specific JavaScript class library, you may try to solve the problems of some class libraries rather than the language. For example, when I try to wrap text (which may also contain HTML elements) with a DIV element. Suppose there are the following HTML:
This is some text and a link
At this time, if you want to convert it to the following:
This is some text and a link
The simplest and most violent method is that you can use it on the parent element. the innerHTML attribute is used for update, but the problem is that all bound event listening will be invalid because an HTML element will be created again when innerHTML is used. This is a big glass! Therefore, JavaScript can only be used for implementation at this time-the size is limited and the size is limited. The following is the implementation code:
Var newWrapper = document. createElement ('P'); while (existingParent. firstChild) {// move the DOM element, no new element newWrapper. appendChild (existingParent. firstChild) is created );}
The for loop cannot be used here, because childNodes is a collection composed of dynamic nodes. Moving a node will affect its index value. We use the while loop to always check the firstChild of the parent element. If it returns a value that represents false, you will know that all nodes have been moved to the new parent!