


How to select and style elements of the first specific class using CSS and JavaScript?
Apr 04, 2025 pm 11:33 PMPrecisely manipulate CSS and JavaScript: Style the first specific class element
In web development, it is often necessary to style the first element of a specific category. For example, the page has multiple elements with class="red" but only the first element is expected to appear in red. This article will demonstrate how to achieve this using CSS and JavaScript.
HTML structure example:
The following HTML code contains multiple class="red" elements:
<div id="test"> <span>I'm span</span> <h1 class="red">I'm h1, just set my style to red</h1> <h1 class="red">I'm h1</h1> <h1 class="red">I'm h1</h1> <h1>I'm h1</h1> </div>
Method 1: JavaScript implementation
JavaScript's document.querySelector()
method can easily select the first matching element. The following code sets the color of the first class="red" element to red:
document.querySelector('.red').style.color = 'red';
Method 2: CSS implementation
The :nth-child()
pseudo-class selector of CSS can be selected according to the order of elements. Combined with the of
keyword, the first element in a specific class can be selected accurately.
.red:nth-child(1 of .red) { color: red; }
To style the last class="red" element, you can use the :nth-last-child()
pseudo-class:
.red:nth-last-child(1 of .red) { color: blue; }
Compatibility Description: It should be noted that :nth-child(n of selector)
and :nth-last-child(n of selector)
may have some problems with browser compatibility. In some older browsers, this method may not work properly. Therefore, which method to choose depends on the project's browser compatibility requirements. If compatibility is critical, JavaScript methods are generally more reliable.
Summary: Both JavaScript and CSS can implement the style setting of the first element of a specific class. Developers should choose the most appropriate method based on actual project requirements and browser compatibility considerations.
The above is the detailed content of How to select and style elements of the first specific class using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The top ten virtual currency trading platforms in Europe in 2025 include Binance, OKX, Coinbase, etc., and are selected based on compliance, security, expenses, asset types and user experience. 1. Binance: The world has the largest transaction volume, low fees, and has obtained a license in multiple countries; 2. OKX: Comprehensive products, strong technology, registered in France; 3. Coinbase: Compliance and safety, suitable for beginners, licensed in many countries; 4. Gate.io: Has a long history, high security, registered in many European countries; 5. Bitstamp: Founded early, has strong compliance, regulated by Luxembourg; 6. eToro: Supports social transactions, diversified investment, regulated by CySEC; 7. Bitpanda: World

HTML5, CSS and JavaScript should be efficiently combined with semantic tags, reasonable loading order and decoupling design. 1. Use HTML5 semantic tags, such as improving structural clarity and maintainability, which is conducive to SEO and barrier-free access; 2. CSS should be placed in, use external files and split by module to avoid inline styles and delayed loading problems; 3. JavaScript is recommended to be introduced in front, and use defer or async to load asynchronously to avoid blocking rendering; 4. Reduce strong dependence between the three, drive behavior through data-* attributes and class name control status, and improve collaboration efficiency through unified naming specifications. These methods can effectively optimize page performance and collaborate with teams.

Binance is a world-renowned digital asset trading platform, providing users with secure, stable and convenient cryptocurrency trading services. Users can buy, sell, manage and market the transactions of hundreds of digital currencies such as Bitcoin and Ethereum anytime, anywhere through their official app.

The latest version of Binance is v2.102.5, and the update tutorial is: 1. Click the download link in the web page; 2. Authorize the installation permission of "Allow installation from unknown sources"; 3. Find the downloaded APk and click to install; 4. Click the installed application to open it.

To identify fake altcoins, you need to start from six aspects. 1. Check and verify the background of the materials and project, including white papers, official websites, code open source addresses and team transparency; 2. Observe the online platform and give priority to mainstream exchanges; 3. Beware of high returns and people-pulling modes to avoid fund traps; 4. Analyze the contract code and token mechanism to check whether there are malicious functions; 5. Review community and media operations to identify false popularity; 6. Follow practical anti-fraud suggestions, such as not believing in recommendations or using professional wallets. The above steps can effectively avoid scams and protect asset security.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The latest version of Binance is v2.102.5, and the update tutorial is: 1. Click the download link in the web page; 2. Authorize the installation permission of "Allow installation from unknown sources"; 3. Find the downloaded APk and click to install; 4. Click the installed application to open it.

list-style is abbreviation attribute in CSS for controlling the pre-marking style of list items. 1. You can set the list-style-type, list-style-position and list-style-image at the same time; 2. By default, unordered lists use disc styles, and ordered lists use numeric numbers; 3. Support setting types, positions and pictures, and specify backup styles to deal with image loading failures; 4. In actual development, the default styles are often cleared to ensure consistency, and pay attention to text indentation and image loading issues.
