首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果文本节点不是父节点的唯一子节点,如何给每个文本节点添加`span`标签?

如果文本节点不是父节点的唯一子节点,如何给每个文本节点添加`span`标签?
EN

Stack Overflow用户
提问于 2020-04-10 10:56:50
回答 1查看 28关注 0票数 0

我想用<span>将其父节点具有其他类型的子节点的每个TEXT_NODE包装起来,以便每个TEXT_NODE都是其父ELEMENT_NODE的唯一子节点。

例如,

代码语言:javascript
复制
<div>
    <button />
    <img />
    text node who has other heterogeneous sibling nodes
    <div>
      only-child text node
    </div>
    another text node
</div>

在操作之后应该成为下面的DOM

代码语言:javascript
复制
<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()来重写非文本独占的节点,但是有没有更好的方法呢?

EN

回答 1

Stack Overflow用户

发布于 2020-04-10 11:56:44

这里有一个可能的解决方案。请阅读代码中的注释以获得解释。

代码语言:javascript
复制
//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]);
  }
});
代码语言:javascript
复制
.added-span {
  border: 1px solid #ff0000;
}
代码语言:javascript
复制
<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>

Link to a fiddle.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61133354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档