CSS select previous sibling element

CSS Select Previous Sibling Element

CSS Select Previous Sibling Element

In CSS, we can use the sibling selector to select the sibling elements of an element. Siblings are elements that share the same parent, but not necessarily adjacent elements. In this article, we’ll delve into how to select an element’s previous sibling.

Using the Sibling Selector

In CSS, we can use the sibling selector (~) to select all of an element’s siblings. If you want to select the previous sibling of an element, you can combine the universal sibling selector (~) with the first-child pseudo-class selector (:first-child).


Here’s a simple example of how to select the previous sibling of an element:

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div ~ span:first-child { 
color: red; }

</style>

</head>

<body>

<div>This is a div element.</div>

<span>This is the first span element.</span>

<span>This is the second span element.</span>

</body>

</html>

In the above example, we select the previous sibling of all <span> elements and set their text color to red. After running this code, the text color of the first <span> element will change to red.

Using JavaScript

If you want to select the previous sibling of an element and perform some operation, you can use JavaScript to achieve this. Here’s a sample code showing how to use JavaScript to select the previous sibling of an element and change its style:

<!DOCTYPE html> 
<html> 
<head> 
<style> 
.selected { 
color: red; 
} 
</style> 
</head> 
<body> 

<div>This is a div element.</div> 
<p>This is the first paragraph element.</p> 
<p>This is the second paragraph element.</p> 

<script> 
const paragraphs = document.querySelectorAll('p'); 
paragraphs.forEach(paragraph => { 
paragraph.addEventListener('click', () => { 
// Select the previous sibling and add a CSS class 
if (paragraph.previousElementSibling) { 
paragraph.previousElementSibling.classList.add('selected'); 
} 
}); 
}); 
</script> 

</body> 
</html> 

In the example above, we first select all <p> elements and add a click event listener to each one. When a <p> element is clicked, its previous sibling (if any) is selected and a CSS class called selected is added to it, changing its text color to red.

Summary

By using sibling selectors and JavaScript, we can easily select and manipulate the previous sibling of an element. This technique can help us create more dynamic and interactive page effects.

Leave a Reply

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