Wednesday, July 25, 2018

css - 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


Answer




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';
}
}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...