我想用<span>将其父节点具有其他类型的子节点的每个TEXT_NODE包装起来,以便每个TEXT_NODE都是其父ELEMENT_NODE的唯一子节点。
例如,
<div>
<button />
<img />
text node who has other heterogeneous sibling nodes
<div>
only-child text node
</div>
another text node
</div>在操作之后应该成为下面的DOM
<div>
<button />
<img />
<span> text node who has other heterogeneous sibling nodes </span> <!-- change made -->
<div>
only-child text node
</div>
<span>another text node</span> <!-- change made -->
</div>我知道我们总是可以使用nodeValue.replace()来重写非文本独占的节点,但是有没有更好的方法呢?
发布于 2020-04-10 11:56:44
这里有一个可能的解决方案。请阅读代码中的注释以获得解释。
//Here, I'm looping through all the elements with .search-elements class in case you have multiple.
//If you only have one, you can remove this part and adapt the code below.
$('.search-elements').each(function(_index, _element) {
var t = $(this); //save the .search-element element for future use.
var nodes = this.childNodes; //an array of all the child nodes (whitespae, button, images, text, etc)
var outputNodes = []; //this will store all the elements that needs to be shown
//loop through all the childNodes
for (var i = 0; i < nodes.length; i++) {
//check if it's type = 3 because 3 is a TEXT_ELEMENT
if (nodes[i].nodeType === 3) {
//now make sure it's not null and check that it's not empty afte removing thewhite spaces
if ((nodes[i].nodeValue !== null) && (nodes[i].nodeValue.trim() !== '')) {
//all good... add it to our outputNodes array
outputNodes.push('<span class="added-span">' + nodes[i].nodeValue + '</span>');
}
} else {
//if it's any other type, just add to the outputNodes array because we want to keep it.
outputNodes.push(nodes[i]);
}
}
t.empty();//now that we know what to keep, empty the container
//loop through all the elements we want to keep and add it to our parent container
for (var j = 0; j < outputNodes.length; j++) {
t.append(outputNodes[j]);
}
});.added-span {
border: 1px solid #ff0000;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-elements">
<button>My button</button>
<img src="https://picsum.photos/20/30" alt=""/>
text node who has other heterogeneous sibling nodes
<div>
only-child text node
</div>
<span>another text node</span>
</div>
https://stackoverflow.com/questions/61133354
复制相似问题