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
Release: 2024-12-28 21:29:10
Original
453 people have browsed it

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';
Copy after login
p {
  background: red;
}

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template