【问题标题】:How do I check an element's direct textContent? [duplicate]如何检查元素的直接文本内容? [复制]
【发布时间】:2020-02-24 03:17:24
【问题描述】:

假设我有这样的元素结构

<div>
   This is direct text

   <div>
       This is text nested in a child element
   </div>
</div>

有没有办法检查父div的直接文本内容而不检查内部孩子的内容?

如果我有这样的结构

<div id="uppermost-div">
  <div>
     This is direct text

     <div>
       This is text nested in a child element
     </div>
   </div>
</div>

我检查了 #uppermost-div 的直接文本内容,我希望它是 null 或空字符串或其他东西。

有没有办法在 HTML/Javascript 中完成检查值?

【问题讨论】:

  • 你现在用什么代码?
  • 我链接到的重复问题询问 jQuery,但也有 vanilla JS 答案。

标签: javascript html innertext


【解决方案1】:

参见 cmets。

// Make a deep copy of the parent
let tempElement = document.getElementById("uppermost-div").cloneNode(true);

// Loop over the elements within the copy
tempElement.querySelectorAll("*").forEach(function(el){
  el.remove(); // remove the children
});

// Log the text of what's left
console.log(tempElement.textContent);
<div id="uppermost-div">
  <div>
     This is direct text

     <div>
       This is text nested in a child element
     </div>
   </div>
</div>

【讨论】:

    【解决方案2】:

    这应该适合你:

    // Get the parent element somehow, you can just as well use
    // .getElementById() or any other DOM method
    var parentElement = document.querySelector('#myDiv');
    // Returns the text content as a string
    [].reduce.call(parentElement.childNodes, function(a, b) { return a + (b.nodeType === 3 ? b.textContent : ''); }, '');
    

    来源:https://medium.com/@roxeteer/javascript-one-liner-to-get-elements-text-content-without-its-child-nodes-8e59269d1e71

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-31
      • 2018-01-21
      • 2023-03-12
      • 2022-01-17
      • 2016-03-20
      • 1970-01-01
      • 2018-07-25
      • 2013-07-13
      相关资源
      最近更新 更多