You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中获取div下未被子节点包裹的文本?

How to Get Direct Text of a Div (Excluding Child Element Text)

Got it, let's tackle this problem. The issue with textContent and innerText is that they pull in all text within the element—including text from child nodes like your <label>. To grab only the direct text (text2 in your example) that belongs directly to parent_div, here are a few reliable approaches:

Approach 1: Iterate Over Child Nodes and Filter Text Nodes

You can loop through the parent element's childNodes collection, check which nodes are text nodes, and extract their content. This lets you skip any element nodes (like the <label>):

const parentDiv = document.getElementById("parent_div");
let directText = "";

// Loop through all child nodes
for (const node of parentDiv.childNodes) {
  // Check if the node is a text node (nodeType 3)
  if (node.nodeType === Node.TEXT_NODE) {
    // Trim to remove extra whitespace and add to our result
    directText += node.textContent.trim();
  }
}

console.log(directText); // Output: "text2"

Approach 2: Use Array Methods for a Concise Solution

If you prefer a more functional style, convert childNodes to an array, filter for text nodes, map to their trimmed content, and join the results:

const parentDiv = document.getElementById("parent_div");
const directText = Array.from(parentDiv.childNodes)
  .filter(node => node.nodeType === Node.TEXT_NODE)
  .map(node => node.textContent.trim())
  .join('');

console.log(directText); // Output: "text2"

Approach 3: Clone the Element and Remove Child Nodes

Another trick is to clone the parent element, remove all its child elements, then get the remaining text. This works because cloning preserves the original element's structure, and removing children leaves only the direct text nodes:

const parentDiv = document.getElementById("parent_div");
const divClone = parentDiv.cloneNode(true);

// Remove all child elements from the clone
while (divClone.firstChild) {
  divClone.removeChild(divClone.firstChild);
}

const directText = divClone.textContent.trim();
console.log(directText); // Output: "text2"

All these methods will target only the text that's directly inside parent_div, ignoring text from child elements like your <label>.

内容的提问来源于stack exchange,提问作者Kuldeep Kala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:32:52