gpt4 book ai didi

javascript - 如何检查元素的直接文本内容?

转载 作者:行者123 更新时间:2023-11-28 03:26:32 25 4
gpt4 key购买 nike

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

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

最佳答案

这应该适合你:

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

关于javascript - 如何检查元素的直接文本内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58598007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com