Home >Web Front-end >CSS Tutorial >How Can I Style the First Instance of a Specific Element Type in an Entire Document?

How Can I Style the First Instance of a Specific Element Type in an Entire Document?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 21:29:10467browse

How Can I Style the First Instance of a Specific Element Type in an Entire Document?

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

Problem:

How can you apply :first-of-type styling to the first element of a particular type anywhere in the document, regardless of its parent element?

CSS Limitations:

CSS's :first-of-type pseudo-class only selects the first sibling of a specific type within its parent element, not across the entire document.

JavaScript Solution:

:first-of-type Class Addition:

  • Add a "first-of-type" class to the first matching element using JavaScript's querySelector() method.
  • Apply styling to elements with the "first-of-type" class.

Example:

document.querySelector('p').className += ' first-of-type';
p {
  background: red;
}

p.first-of-type {
  background: pink;
}
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>

This solution ensures that the first paragraph in the entire document, regardless of its location, receives the "first-of-type" styling.

The above is the detailed content of How Can I Style the First Instance of a Specific Element Type in an Entire Document?. 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