【问题标题】:How to add a `span` tag to every text node who is not the only child of his parent node?如何为每个不是其父节点唯一子节点的文本节点添加“跨度”标签?
【发布时间】:2020-04-10 02:56:49
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery html dom


    【解决方案1】:

    这是一个可能的解决方案。请阅读代码中的 cmets 进行解释。

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

    Link to a fiddle.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多