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?
In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items.
The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".
The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With