We have a DOM like this:
<div class="outer">
<div class="inner"> <!--// No "copyright" in this node //-->
<div class="content">...</div>
</div>
<div class="inner">
<div class="content">...</div>
<div class="copyright">...</div> <!--// DISPLAY THIS ONE //-->
</div>
<div class="inner">
<div class="content">...</div>
<div class="content">...</div>
<div class="content">...</div>
<div class="copyright">...</div> <!--// Hide this one //-->
</div>
<div class="inner">
<div class="content">...</div>
<div class="content">...</div>
<div class="copyright">...</div> <!--// Hide this one too, etc. //-->
</div>
<!--// etc. //-->
</div>
All elements with class "copyright" must be hidden, with exception of the very first one.
We tried to apply this approach, but unfortunately with no success. It must be a CSS only solution. Any idea?
Thanks for your help!
The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)
Approach: Use the :not(selector), also known as negation pseudo-class which takes a simple selector as an argument and allows you to style all the elements except the element specified by the selector.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.
In this case, each .copyright
is the first and only one of its kind in .inner
, so you need to select by .inner
instead. If you don't need to apply any special rules to the first child, you don't need to use the approach I describe in that other question; simply use this to hide the other elements:
.inner ~ .inner .copyright {
display: none;
}
This is still the top answer on Google for "css select first occurrence of class" so adding the simple technique I found to work.
This solution doesn't specifically solve the OP but does allow you to select the first element with a class amongst siblings.
You can use a combination of the sibling and not selectors as shown in this JSFiddle
For example:
.my-class:not(.my-class ~ .my-class) {
background: red;
}
How does this work?
The sibling selector (~
) selects elements which are somewhere after other elements.
So this would select every element except the first one:
.my-class ~ .my-class {
background: red;
}
We then just use the :not
selector to reverse this, i.e. select only the first element.
I have only tested this on Chrome but think it should work on most modern browsers.
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