Home >Web Front-end >JS Tutorial >Use JavaScript to wrap text element nodes with a DIV_javascript skills

Use JavaScript to wrap text element nodes with a DIV_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:36:521339browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn