Search code examples
jqueryclassnumerical

Get numerical value at end of class name and store as variable using jQuery


Consider this menu output by a WordPress function:

<ul id="header-cats"> 

    <li class="cat-item cat-item-6"><a href="url" title="View all posts filed under Category I">Category I</a> 
</li> 
    <li class="cat-item cat-item-7"><a href="url" title="View all posts filed under Category II">Category II</a> 
</li> 
    <li class="cat-item cat-item-8"><a href="url" title="View all posts filed under Category III">Category III</a> 
</li> 

</ul> 

Now consider this list of posts:

<ul id="posts-preview" class="clearfix"> 

    <li class="filter-reset filter-hide filter-6 ">             
        <a class="post-thumb" id="post-112" href="url" >Link</a>        
    </li>

    <li class="filter-reset filter-hide filter-6 filter-8 ">            
        <a class="post-thumb" id="post-102" href="url" >Link</a>        
    </li>

    <li class="filter-reset filter-hide filter-7 ">             
        <a class="post-thumb" id="post-88" href="url" >Link</a>         
    </li>

    <li class="filter-reset filter-hide filter-6 ">             
        <a class="post-thumb" id="post-6" href="url" >Link</a>      
    </li>
</ul>

My aim is to use a jQuery function to extract the numerical ending of the menu's class name (ie. the 6 in cat-item 6) and use that value to target the corresponding post. To elaborate I would use that 6 as a variable and find the filter class that ends in 6.

Here is what I have so far:

  $('#header-cats li').click(function(){  

    var num_id = $(this).attr('class') // ... matching "cat-item-?" etc...

        $(".filter-"+num_id).fadeIn(500); 

        return false;

  });

Should be easy for a js fiend :-)


Solution

  • You could use a RegEx to get the number from your class id (code below not tested) -

    $('#header-cats li').click(function(){  
        var num_id = $(this).attr('class').match(/\d+/); // ... matching "cat-item-?" etc...
        $(".filter-"+num_id).fadeIn(500); 
        return false;
    });