Home >Web Front-end >CSS Tutorial >How to Style the First Instance of an Element Type in HTML Using CSS or JavaScript?
Question:
How can one utilize CSS or JavaScript to target and style the initial occurrence of a particular element type across the entire HTML document, irrespective of its placement within the document structure?
Answer:
CSS-based Solution
Unfortunately, CSS alone does not provide functionality to match the first occurrence of an element type across the entire document. The :first-of-type pseudo-class, as per CSS specifications, only applies to the first sibling of its type within its parent element.
JavaScript-based Solutions
1. :first-of-type Emulation
Using JavaScript, we can achieve this functionality by introducing a custom class, "first-of-type," and utilizing the querySelector() method to retrieve the first matching element of the desired type. We then assign this custom class to the retrieved element:
document.querySelector('p').className += ' first-of-type';
2. Custom Matching Function
We can also develop a custom JavaScript function to identify and style the first occurrence of a specific element type:
function nthIndexOfType(element, index) { var siblings = element.parentElement.children; var count = 1; for (var i = 0; i < siblings.length; i++) { if (siblings[i].tagName === element.tagName) { if (count === index) { return siblings[i]; } count++; } } return null; } nthIndexOfType(document.querySelector('p'), 1).style.backgroundColor = 'pink';
This function accepts two parameters: the element we want to search for and the index of the occurrence we want to target. It iterates through all sibling elements and returns the first element of the specified type, applying the desired styling.
The above is the detailed content of How to Style the First Instance of an Element Type in HTML Using CSS or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!