Use JavaScript to wrap text element nodes

Source: Internet
Author: User

Original link: Wrapping Text Nodes and Elements with JavaScript original date: 2014-09-04 translation Date: 2014-09-06 Translator: Anchor
When your application relies on a particular JavaScript class library, you inadvertently try to solve some of the library's own problems, not the language. Just like when I try to wrap the 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>.

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 method of violence is that you can use the parent element to . InnerHTMLproperty to perform the update, but the problem is that all of the bound event listeners will fail because the InnerHTML, an HTML element is recreated. This is really a big glass! So this time can only use JavaScript to achieve-the ruler has a short, inch. Here is the implementation code:
var newwrapper = document.createelement (' div '); while (Existingparent.firstchild) {    //move DOM element, no new element    created Newwrapper.appendchild (existingparent.firstchild);}

The For loop cannot be used here because ChildNodesis a collection of dynamic nodes that can affect the index value of a node as long as it is moved. We use whileThe loop always detects the parent element's FirstChild, if it returns a value that represents false, then you know that all the nodes have been moved to the new parent!

Use JavaScript to wrap text element nodes

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.