I'm trying to target a class element (appearing more than once in the DOM) by its index or iteration, strictly using CSS.
I know of several different ways of achieving this: I could toss the element(s) in an array and retrieve a specific index of said element (Javascript). I could label the element I'm trying to target with an #ID. I could refine the targeted element by specifying an attribute (.element[href="link"]
). The pseudo-class :first-child
and :last-child
only target the children of that (parent) element (Duh!).
Example: I have a .class
appearing 5 times within my DOM and I want to affect the CSS properties of the 3rd iteration of that .class
element.
I wish there was a pseudo-class of .element:index-3.
There's probably something out there that let's you do just that.
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. To do this, start with the element name, then write the period (.)
A CSS selectors provides more ways for matching elements by examining where they are situated in the document metatree. They are considered to be child-indexed pseudo-classes since the position or order of the element determines the type, attributes, or IDs attached to it.
In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).
If I understand you correctly, you want to style the element with the content "Me!" in this example:
<body>
<p>Not me.</p>
<p class="me">Not me.</p>
<div><p class="me">Not me.</p></div>
<p class="me">Me!</p>
<div><div><p class="me">Not me.</p></div></div>
<p class="me">Not me.</p>
</body>
This should be possible In some cases (see below) it is possible with the pseudo-class :nth-of-type
:
.me:nth-of-type(3) {color:red;}
As ScottS noted in the comments, this is only possible if all classes are on the same element type (e.g. p
).
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