Question

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])

Was it helpful?

Solution

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's and, after it finds the correct siblings it caches it for future use to speed up the execution:

$(function(){
    $("li").hover(function(){
        var $this    = $(this),
            $cache   = $this.data('hoverCache');

        if(!$cache){
            var category = this.className.match(/category\-.+?\b/)      
            $this.data('hoverCache', $this.siblings('.' + category).andSelf().addClass('hover') );
        } else {
            $cache.addClass('hover');
        }

    }, function(){
        var $cache = $(this).data('hoverCache');
        if($cache) $cache.removeClass('hover');
    });
})

So it doesn't get lost in this optimized example, here is the relevant code to your question:

var category = this.className.match(/category\-.+?\b/);
$(this).siblings('.' + category).andSelf();

This finds the category from the className (there can be additional classes) and then it finds other children of the same parent using .siblings and then includes itself so you can add the hover class 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!

OTHER TIPS

You can use the attributeStartsWith selector:

$("li[class^=category]").hover(/*...*/);

Check an example with your markup here.

Edit: To get the class name you can use this.className or, use the attr function, for example:

$("li[class^=category]").each(function(){
  var className = $(this).attr('className');  
  // this.className, or attr('class'), which will be mapped to className
});

And by the way, you can also use the filter(fn) method to select the li elements which their className starts with 'category':

$("li").filter(function () {
  return /category-.+/.test(this.className);
}).hover(/*...*/);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top