如何获取最外层DOM元素的文本?

问题描述 投票:0回答:1

我正在创建一个 Chrome 扩展程序。当用户单击 div 时,它会返回 div 内的所有元素。但我只需要访问标签之外的文本。

这是我编写的函数,但它为我提供了

<div>
标签内的整个文本。

function getData(e) {
  var li = e.currentTarget;
  return li.innerText;
}

<div class="msg">
I started painting as a hobby when I was little. I didn't know I had any talent. I   believe talent is just a pursued interest. 

Anybody can do what I do. Just go back and put one little more happy tree in there. Everybody's different. Trees are different. 

Let them all be individuals. We'll put some happy little leaves here and there. These things happen automatically. 

<reactions class="xyz">
 <reaction class="ABC">
  <span> 27 </span>
  <span> 2 </span>
  <span> 12 </span>
 </reaction>
</reactions>

</div>

我尝试循环返回的 DOM 元素,但是返回的元素是如此动态,以至于它不起作用。

javascript dom google-chrome-extension
1个回答
0
投票

您可以尝试以下方法:

function getData() {
  const divElement = document.querySelector('.msg');
  const textNodes = Array.from(divElement.childNodes) //get all child nodes
                      //filter for text nodes directly within the div
                      .filter(node => node.nodeType === Node.TEXT_NODE && node.parentNode === divElement);
  //concatenate text content
  const textContent = textNodes.map(node => node.textContent.trim()).join(' '); 
  console.log(textContent);
}
<div class="msg" onclick="getData()">
    I started painting as a hobby when I was little. I didn't know I had any talent. I believe talent is just a pursued interest.
    Anybody can do what I do. Just go back and put one little more happy tree in there. Everybody's different. Trees are different.
    Let them all be individuals. We'll put some happy little leaves here and there. These things happen automatically.
    <reactions class="xyz">
        <reaction class="ABC">
            <span>27</span>
            <span>2</span>
            <span>12</span>
        </reaction>
    </reactions>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.