gpt4 book ai didi

javascript - 如何在javascript中获取没有ID的元素的文本内容

转载 作者:行者123 更新时间:2023-11-30 14:00:43 27 4
gpt4 key购买 nike

我想获取标题元素的特定文本内容,它没有任何关联的 ID。我应该使用什么 javascript 代码来获取内容“我只想要这个”。

var elements = document.querySelectorAll('.one span');
console.log(elements[0].text);

这段代码没有给出想要的输出

<h5 class="one two three four">
<span class="s1 s2">I don't want this</span>
I only want this one</h5>

我希望输出是“我只想要这个”,但我变得不确定...

最佳答案

您要选择的不是元素的文本节点,因此您不能立即使用querySelectorAll(或querySelector) - 因此,首先选择父级(.one),然后导航到它的最后一个子级:

const parent = document.querySelector('.one');
const textNode = parent.lastChild;
console.log(textNode.textContent);
<h5 class="one two three four">
<span class="s1 s2">I don't want this</span>
I only want this one</h5>

请注意,如果您只想要匹配特定选择器字符串的第一个元素,则使用 querySelector(返回该元素)比使用 querySelectorAll 更合适(它返回一个集合,您必须从中继续选择其中的第一个元素)。

关于javascript - 如何在javascript中获取没有ID的元素的文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351293/

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