有没有办法只获取顶部元素的innerText(并忽略子元素的innerText)?

发布于 2025-01-06 10:50:21 字数 244 浏览 0 评论 0原文

有没有办法只获取顶部元素的innerText(并忽略子元素的innerText)?

示例:

<div> 
   top node text 
   <div> child node text </div>
</div>

如何获取“顶部节点文本”而忽略“子节点文本”?顶部 div 的 innerText 属性似乎返回内部文本和顶部文本的串联。

Is there a way to get innerText of only the top element (and ignore the child element's innerText) ?

Example:

<div> 
   top node text 
   <div> child node text </div>
</div>

How to get the "top node text" while ignoring "child node text" ? innerText property of top div seem to return concatenation of both inner , top text.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

(り薆情海 2025-01-13 10:50:21

只需迭代子节点并连接文本节点:

var el = document.getElementById("your_element_id"),
    child = el.firstChild,
    texts = [];

while (child) {
    if (child.nodeType == 3) {
        texts.push(child.data);
    }
    child = child.nextSibling;
}

var text = texts.join("");

Just iterate over the child nodes and concatenate text nodes:

var el = document.getElementById("your_element_id"),
    child = el.firstChild,
    texts = [];

while (child) {
    if (child.nodeType == 3) {
        texts.push(child.data);
    }
    child = child.nextSibling;
}

var text = texts.join("");
染火枫林 2025-01-13 10:50:21

这将在您的示例中起作用:
document.getElementById("item").firstChild.nodeValue;

注意:请记住,如果您知道自己正在处理特定的 HTML,那么这将起作用。如果您的 HTML 可以更改,例如:

<div> 
    <div class="item"> child node text </div>
    top node text 
</div>

那么您应该使用 @Tim Down

提供的更通用的解决方案


这是工作代码片段:

window.onload = function() {
   var text = document.getElementById("item").firstChild.nodeValue;
   document.getElementById("result").innerText = text.trim();
};
#result {
  border: 1px solid red;
}
<div id="item">
  top node text 
   <div> child node text </div>
</div>



<strong>Result:</strong> <div id="result"></div>

This will work in your example:
document.getElementById("item").firstChild.nodeValue;

Note: Keep in mind that this will work if you know you are dealing with that specific HTML. If your HTML can change, for example to:

<div> 
    <div class="item"> child node text </div>
    top node text 
</div>

then you should use the more generic solution by @Tim Down


Here is working code snippet:

window.onload = function() {
   var text = document.getElementById("item").firstChild.nodeValue;
   document.getElementById("result").innerText = text.trim();
};
#result {
  border: 1px solid red;
}
<div id="item">
  top node text 
   <div> child node text </div>
</div>



<strong>Result:</strong> <div id="result"></div>

萌逼全场 2025-01-13 10:50:21
  1. 克隆元素。
  2. 循环遍历所有子节点(向后,以避免冲突):
    如果元素具有 tagName 属性,则它是一个元素:删除该节点。
  3. 使用 innerText 获取文本内容(当不支持 innerText 时,回退到 textContent)。

代码:

var elem = document.getElementById('theelement');
elem = elem.cloneNode(true);
for (var i=elem.childNodes.length-1; i>=0; i--) {
    if (elem.childNodes[i].tagName) elem.removeChild(elem.childNodes[i]);
}
var innerText = elem['innerText' in elem ? 'innerText' : 'textContent'];
  1. Clone the element.
  2. Loop through all child nodes (backwards, to avoid conflicts):
    If the element has a tagName attribute, then it's an element: Remove the node.
  3. Use innerText to get the textual contents (with fallback to textContent, when innerText is not supported).

Code:

var elem = document.getElementById('theelement');
elem = elem.cloneNode(true);
for (var i=elem.childNodes.length-1; i>=0; i--) {
    if (elem.childNodes[i].tagName) elem.removeChild(elem.childNodes[i]);
}
var innerText = elem['innerText' in elem ? 'innerText' : 'textContent'];
多像笑话 2025-01-13 10:50:21
function getDirectInnerText(element) {
  var childNodes = element.childNodes;
  result = '';

  for (var i = 0; i < childNodes.length; i++) {
    if(childNodes[i].nodeType == 3) {
      result += childNodes[i].data;
    }
  }

  return result;
}

element = document.querySelector("div#element");
console.log(getDirectInnerText(element))
<div id="element"> 
   top node text 
   <div> child node text </div>
</div>

function getDirectInnerText(element) {
  var childNodes = element.childNodes;
  result = '';

  for (var i = 0; i < childNodes.length; i++) {
    if(childNodes[i].nodeType == 3) {
      result += childNodes[i].data;
    }
  }

  return result;
}

element = document.querySelector("div#element");
console.log(getDirectInnerText(element))
<div id="element"> 
   top node text 
   <div> child node text </div>
</div>

千笙结 2025-01-13 10:50:21

正如所有其他答案已经解释的那样,您需要检查子节点的类型。

这是基于 @ehsaneha 的答案的简洁单行:

Array.from(element.childNodes).reduce((x, y) => x + (y.nodeType == Node.TEXT_NODE ? y.data : ''), '').trim()

或者作为原型方法:

Element.prototype.directInnerText = function () {
    return Array.from(this.childNodes).reduce((x, y) => x + (y.nodeType == Node.TEXT_NODE ? y.data : ''), '').trim();
}

用法:

console.log(document.body.querySelector('.element').directInnerText());

兼容性参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://developer.mozilla.org/ en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/ en-US/docs/Web/API/Node/nodeType?retiredLocale=de

As every other answer already explained, you need to check the type of the childnode.

Here is a neat one-liner based on @ehsaneha's answer:

Array.from(element.childNodes).reduce((x, y) => x + (y.nodeType == Node.TEXT_NODE ? y.data : ''), '').trim()

Or as a prototyped method:

Element.prototype.directInnerText = function () {
    return Array.from(this.childNodes).reduce((x, y) => x + (y.nodeType == Node.TEXT_NODE ? y.data : ''), '').trim();
}

usage:

console.log(document.body.querySelector('.element').directInnerText());

Compatibility reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType?retiredLocale=de

〆一缕阳光ご 2025-01-13 10:50:21

如果您不想忽略子元素的内部文本,请使用以下函数:

function getInnerText(el) {
    var x = [];
    var child = el.firstChild;
    while (child) {
        if (child.nodeType == 3) {
            x.push(child.nodeValue);
        }
        else if (child.nodeType == 1) {
            var ii = getInnerText(child);
            if (ii.length > 0) x.push(ii);
        }
        child = child.nextSibling;
    }
    return x.join(" ");
}

If you don't want to ignore the child element's inner text, use the following function:

function getInnerText(el) {
    var x = [];
    var child = el.firstChild;
    while (child) {
        if (child.nodeType == 3) {
            x.push(child.nodeValue);
        }
        else if (child.nodeType == 1) {
            var ii = getInnerText(child);
            if (ii.length > 0) x.push(ii);
        }
        child = child.nextSibling;
    }
    return x.join(" ");
}
恰似旧人归 2025-01-13 10:50:21
const nodeValues=[];
document.querySelectorAll("locator").forEach(
    function (currentValue) {
        nodeValues.push(currentValue.firstChild.nodeValue);
    }
)
return nodeValues;
const nodeValues=[];
document.querySelectorAll("locator").forEach(
    function (currentValue) {
        nodeValues.push(currentValue.firstChild.nodeValue);
    }
)
return nodeValues;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文