如何选择没有属性的元素

oba*_*net 5 javascript

所以我在一个 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>
Run Code Online (Sandbox Code Playgroud)

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

此外,与一流的元素one有时会出现有时不会,所以我不能与一些喜欢选择它: [1]

最好的方法是什么?

Cer*_*nce 4

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

const div = document.querySelector('div');
const spanWithNoAttributes = [...div.children]
  .find(span => span.attributes.length === 0);
spanWithNoAttributes.textContent = 'THIS ONE HERE';
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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