繁体   English   中英

如何为每个不是其父节点唯一子节点的文本节点添加“跨度”标签?

[英]How to add a `span` tag to every text node who is not the only child of his parent node?

我想用<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()来重写非文本专有节点,但是有更好的方法吗?

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

 //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>

链接到小提琴。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM