


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

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.

In the ever-changing virtual currency market, timely and accurate market data is crucial. The free market website provides investors with a convenient way to understand key information such as price fluctuations, trading volume, and market value changes of various digital assets in real time. These platforms usually aggregate data from multiple exchanges, and users can get a comprehensive market overview without switching between exchanges, which greatly reduces the threshold for ordinary investors to obtain information.

The OEX official website entrance is the primary channel for users to enter the OEX (OEX) platform. The platform is known for its safety, efficiency and convenience, and provides currency trading, contract trading, financial management services, etc. 1. Visit the official website; 2. Click "Register" to fill in your mobile phone number or email address; 3. Set your password and verify; 4. Log in after successful registration. The platform's advantages include high security, simple operation, rich currency, and global service. It also provides beginner's guidance and teaching modules, suitable for all types of investors.

Dogecoin, Pepe and Brett are leading the meme coin craze. Dogecoin (DOGE) is the originator, firmly ranked first in the market value list, Pepe (PEPE) has achieved hundreds of times increase with its social geek culture, and Brett (BRETT) has become popular with its unique visual style as a new star in Base chain; the three were issued in 2013, 2023 and 2024 respectively. Technically, Dogecoin is based on Litecoin, Pepe and Brett are ERC-20 tokens, and the latter relies on the Base chain to improve efficiency. In terms of community, DOGE Twitter fans have exceeded 3 million, Pepe Reddit is leading in activity, Brett's popularity in Base chain, and DOGE has logged in on the platform.

opacity is an attribute in CSS that controls the overall transparency of an element, with values ranging from 0 (fully transparent) to 1 (fully opaque). 1. It is often used for the image hover fade effect, and enhances the interactive experience by setting the opacity transition; 2. Making a background mask layer to improve text readability; 3. Visual feedback of control buttons or icons in the disabled state. Note that it affects all child elements, unlike rgba, which only affects the specified color part. Smooth animation can be achieved with transition, but frequent use may affect performance. It is recommended to use it in combination with will-change or transform. Rational application of opacity can enhance page hierarchy and interactivity, but it should avoid interfering with users.

Altcoins worth paying attention to in 2025 include Solana (SOL), Chainlink (LINK), Near Protocol (NEAR) and Arbitrum (ARB), which have advantages in transaction speed, cross-chain infrastructure, user-friendliness and the Layer 2 ecosystem, and can be obtained on mainstream platforms. 1. Solana has become the first choice for high-frequency applications with high TPS and low fees. Firedancer will enhance its performance when it launches; 2. Chainlink, as a key oracle project, plays an important role in RWA and cross-chain interoperability; 3. Near lowers the Web3 threshold through human readable accounts and AI strategies to promote

InCSS,propertyinheritanceaffectshowstylesarepassedfromparentelementstochildren.Somepropertieslikecolorandfont-familyinheritbydefault,applyingtoallnestedelementsunlessoverridden.Non-inheritedpropertiessuchasborder,margin,andpaddingmustbesetexplicitly.

The official website of OK exchange is okx.com, and users need to access it through secure channels to ensure account security. 1. The official website provides multi-language support and transaction portal; 2. Confirm the URL when accessing and has an SSL certificate; 3. Regularly update the browser and security software; 4. Use official APP or certified application store to download; 5. Enable two-step verification to enhance account protection; 6. Prevent phishing websites and do not click unknown links; 7. Beware of fake customer service fraud; 8. Change access channels in time when abnormalities are found.
