Home >Web Front-end >CSS Tutorial >How to Select the First Instance of a Specific Element Type in an Entire Document Using CSS?
Question:
How can you specify the first instance of a particular element type in an entire document using CSS?
Answer:
Regular CSS doesn't allow for matching the first element of a specific type across the entire document. This is because the :first-of-type pseudo-class only applies to elements relative to their parent instead of the document root.
You can approximate the functionality of :first-of-type with JavaScript using the querySelector() method, which retrieves the first matching element from the specified selector. Here's an example:
document.querySelector('p').className += ' first-of-type';
p { background: red; } p.first-of-type { background: pink; }
This code assigns the "first-of-type" class to the first
element in the document, allowing you to style it independently:
<body> <section> <p>111</p> <p>222</p> <p>333</p> </section> <p>444</p> <p>555</p> </body>
The above is the detailed content of How to Select the First Instance of a Specific Element Type in an Entire Document Using CSS?. For more information, please follow other related articles on the PHP Chinese website!