gpt4 book ai didi

javascript - 如何选择没有属性的元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:40:49 26 4
gpt4 key购买 nike

所以我在一个 div 中有几个跨度,其中大部分都有类或其他属性。

<span class="one" attribute="test"></span>
<span></span> /* This is what i need to select */
<span class="three" attribute="test"></span>
<span class="four" attribute="test"></span>
<span></span>

我想选择第一个没有属性的跨度,但还要确保不会选择最后一个没有属性的跨度。

此外,类为 one 的元素有时会出现,有时不会出现,因此我无法使用诸如 [1] 之类的数字来选择它。

什么是最好的方法?

最佳答案

您可以通过检查其 attributes 属性的长度来查看一个元素具有多少个属性:

const div = document.querySelector('div');
const spanWithNoAttributes = [...div.children]
.find(span => span.attributes.length === 0);
spanWithNoAttributes.textContent = 'THIS ONE HERE';
<div>
<span class="one" attribute="test">one</span>
<span>two</span>
<span class="three" attribute="test">three</span>
<span class="four" attribute="test">four</span>
<span>five</span>
</div>

您还应该修正您的 HTML - 结束标签应该在标签名称​​之前有一个斜线,而不是之后。

关于javascript - 如何选择没有属性的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50011892/

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