oban_internet
oban_internet

Reputation: 229

How to select an element that has no attributes

So i have couple of spans within a div and most of them have classes or other attributes.

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

I would like to select the very first span that has no attributes but also make sure that the last span that has no attributes wont be selected.

Also, the element with class one will sometimes appear and sometimes wont so i can't select it with a number like: [1].

What would be the best approach?

Upvotes: 5

Views: 2031

Answers (3)

Studocwho
Studocwho

Reputation: 2478

If the order of spans is the same, and if the span never gets attributes, then you could just use the nth-child selector.

With jQuery...

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

Upvotes: 1

user2437417
user2437417

Reputation:

If you need to make sure there are no attributes at all, you'll need to select the elements by tag (or globally) and perform a filter.

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

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

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

However, be aware that there are legacy browsers that may automatically set some attributes in the .attributes list, so this may not work in all cases.


If you only need to prevent those with a specific attribute or set of attributes, you can use the :not() selector with the "has attribute" selector.

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

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

If there are other specific ones to prevent, you can add more :not() selectors. "span:not([attribute]):not([id]):not([class])"

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370729

You can check to see how many attributes an element has by checking the length of its attributes property:

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>

You should also fix up your HTML - end tags should have a slash before the tag name, not after.

Upvotes: 4

Related Questions