willf
willf

Reputation: 41

Select all sibling elements, not just following ones

The intent is to target all the other elements of the same type & same level whenever one is hovered. Tried

a:hover ~ a

Only to notice that this doesn't target the elements before the hovered one... Is there a solution with css? Or should I just somehow js my way out of this

Upvotes: 1

Views: 1662

Answers (2)

Nathan
Nathan

Reputation: 11149

This is a variation on the parent or < selector question (of which there are many). I know it's not quite the same, but I'm sure you can imagine how a sibling selector would be derived from a parent selector.

Jonathan Snook has an excellent blog post on why this doesn't exist, and I don't think I can do any better, so I'll leave you to read that if it interests you. Basically, it's a technically difficult job because of the way elements are selected, and it would lead to a whole world of mess in terms of code structure.

So the short answer is, this doesn't exist and you'll need to resort to JS to fix it, I'm afraid.

Edit: Just a couple of examples of fixes. Using jQuery:

$(selector).siblings().css({...});

or if you want to include the element:

$(selector).parent().children().css({...});

Or in vanilla JS:

var element = document.querySelectorAll(selector); // or getElementById or whatever
var siblings = element.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
    if (siblings[i] !== element) { // optional
        siblings[i].style.color = 'red';
    }
}

Upvotes: 4

daGUY
daGUY

Reputation: 28753

You can do this by using jQuery to toggle the hover states instead of CSS:

HTML:

​<div>
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

CSS:

div a {color: #000;}
div a.hover {color: #00f;}

​ jQuery:

$("div a").hover(
    function(){
        $("div a").addClass("hover");
    },
    function(){
        $("div a").removeClass("hover");
    }
);

Fiddle

Upvotes: 1

Related Questions