如何检查元素的直接textContent?

时间:2019-10-28 20:32:56

标签: javascript html innertext

说我有一个像这样的元素结构

<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中那样检查值?

2 个答案:

答案 0 :(得分:0)

这应该对您有用:

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

答案 1 :(得分:0)

查看评论。

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