rob.m rob.m - 1 year ago 57
jQuery Question

Add class to elments with same matching class as per clicked element

I need to add an

class to any button which matches any of the classes as per the div I am clicking:

<button class="valueA"></button>
<button class="valueB"></button>
<button class="valueC valueB"></button>

<div class="DYNAMIC CLASS"></div>

$("div.valueB").on("click", function() {

The result should be:

<button class="valueB active"></button>
<button class="valueC valueB active"></button>

I tried using
but I'm stack with the comparison of the classes.

The thing is that my div has dynamic class just as well as those buttons, so I don't know what matches until they are in the DOM.

Answer Source

One version is to create a click function for every single class that you have in your document. This would look something like this:

$('.valueA').click(function() {
$('.valueB').click(function() {
$('.valueC').click(function() {

This is repetitive code however and should be avoided. So instead you can create a function that adds click handlers to all buttons (that's the example I wrote) and then retrieves the classes attached to the element. It then loops over the array of classes and adds to every element with that class another one.

$('button').click(function() {
    var classes = $(this).attr('class').split(' ')
  classes.forEach(function(elem) {

    $('.' + elem).addClass('active');

Now if you want to limit the application of said class then you add the element type that the class should be applied to before the .

$('button.' + elem).addClass('active');


$('div.' + elem).addClass('active');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download