Use JavaScript to implement a DIV to wrap text element node _ javascript skills

Source: Internet
Author: User
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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.