CSS same class name select the second

CSS: Selecting the Second of the Same Class Name

In CSS, when we have multiple elements with the same class name, sometimes we need to select the second element for styling. This is a common requirement in real-world development. This article will introduce several methods to achieve this goal.

Method 1: Use the :nth-of-type pseudo-class to select the second element

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>CSS selects the second element with the same class name</title> 
<style> 
.example { 
color: red; 
} 
.example:nth-of-type(2) { 
color: blue; 
} 
</style> 
</head> 
<body> 
<p class="example">first element</p> 
<p class="example">second element</p> 
<p class="example">third element</p> 
</body> 
</html> 

Output:

CSS selects the second element with the same class name


In the example above, we use :nth-of-type(2) to select the second element with the class name example and set its color to blue.

Method 2: Use the :nth-child pseudo-class to select the second element

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>CSS selects the second element with the same class name</title> 
<style> 
.example { 
color: red; 
} 
.example:nth-child(2) { 
color: blue; 
} 
</style> 
</head> 
<body> 
<p class="example">First element</p> 
<p class="example">Second element</p> 
<p class="example">The third element</p> 
</body> 
</html> 

Output:

CSS same class name select the second

In this example, we use :nth-child(2) to select the second element with the class name example and set its color to blue.

Method 3: Use JavaScript to select the second element and add a class name

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>CSS Select the Second Element with the Same Class Name</title> 
<style> 
.example { 
color: red; 
} 
.blue { 
color: blue; 
} 
</style> 
</head> 
<body> 
<p class="example">First Element</p> 
<p class="example">Second Element</p> 
<p class="example">Third Element</p> 

<script> 
const elements = document.querySelectorAll('.example'); 
elements[1].classList.add('blue'); 
</script> 
</body> 
</html> 

Output:

CSS same class name select the second

In this example, we use JavaScript to select the second element with the class name “example” and add the class name “blue” to it, thereby changing its color to blue.

Leave a Reply

Your email address will not be published. Required fields are marked *