I’m trying to group related elements using class name. They, in turn, are all related as they are all using the same prefix for the class name. Example:
<ul>
<li class="category-fruit"></li>
<li class="category-grain"></li>
<li class="category-meat"></li>
<li class="category-fruit"></li>
<li class="category-meat"></li>
</ul>
Visually, I want a hover function on each that, when hovered, will apply the same visual effect to the other elements sharing the same class name.
While it’s easy to select a particular LI with a particular class, how would I go about picking a particular class from the hovered LI?
So in pseudo code
$("li").hover(function(){
$(this).[get-the-class-beggining-with"category"]
})
I’m guessing this involves using the starts with selector ([attribute^=value])
Following @CMS’s awesome lead, I have posted a working example of this solution to JSBin.
I have come up with a solution that allows you to have additional classes on the
li'sand, after it finds the correct siblings it caches it for future use to speed up the execution:So it doesn’t get lost in this optimized example, here is the relevant code to your question:
This finds the category from the
className(there can be additional classes) and then it finds other children of the same parent using.siblingsand then includes itself so you can add thehoverclass to the elements at one time.I tested this code using Firefox and your provided HTML and it worked great. Let me know if its not what you needed!