如何选择没有属性的元素

时间:2018-04-24 23:09:48

标签: 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>

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

此外,有时会出现带有one类的元素,有时候不会出现这样的情况,因此我无法使用以下数字选择它:[1]

最好的方法是什么?

3 个答案:

答案 0 :(得分:3)

您可以通过检查其attributes属性的长度来检查元素的属性数量:

&#13;
&#13;
const div = document.querySelector('div');
const spanWithNoAttributes = [...div.children]
  .find(span => span.attributes.length === 0);
spanWithNoAttributes.textContent = 'THIS ONE HERE';
&#13;
<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>
&#13;
&#13;
&#13;

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

答案 1 :(得分:1)

如果跨度的顺序相同,并且跨度永远不会获得属性,那么您可以使用nth-child选择器。

使用jQuery ......

$("span:nth-child(2)").blah.blah;

答案 2 :(得分:0)

如果您需要确保根本没有属性,则需要按标签(或全局)选择元素并执行过滤。

&#13;
&#13;
var spans = Array.from(document.querySelectorAll("span"));

var noattrs = spans.find(s => !s.attributes.length);

alert(noattrs.outerHTML);
&#13;
<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>
&#13;
&#13;
&#13;

但是,请注意,有些旧版浏览器可能会自动在.attributes列表中设置某些属性,因此这可能并不适用于所有情况。

如果您只需要阻止具有特定属性或属性集的用户,则可以将:not()选择器与&#34; has属性&#34;一起使用。选择器。

&#13;
&#13;
var noattr = document.querySelector("span:not([attribute])");

alert(noattr.outerHTML);
&#13;
<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>
&#13;
&#13;
&#13;

如果还有其他特定问题需要阻止,您可以添加更多:not()个选择器。 "span:not([attribute]):not([id]):not([class])"