Home >Web Front-end >CSS Tutorial >How to Select the First Instance of a Specific Element Type in an Entire Document Using CSS?

How to Select the First Instance of a Specific Element Type in an Entire Document Using CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 22:52:12597browse

How to Select the First Instance of a Specific Element Type in an Entire Document Using CSS?

Matching the First Element of a Specific Type Anywhere in the Document

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.

JavaScript Solutions

Simulating :first-of-type

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn