如何在JavaScript中获取div下未被子节点包裹的文本?
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

