javascript - Add class to elments with same matching class as per clicked element -
i need add .active
class button matches of classes per div 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 .each()
i'm stack comparison of classes.
the thing div has dynamic class buttons, don't know matches until in dom.
one version create click function every single class have in document. this:
$('.valuea').click(function() { $('.valuea').addclass('active') }) $('.valueb').click(function() { $('.valueb').addclass('active') }) $('.valuec').click(function() { $('.valuec').addclass('active') })
this repetitive code , should avoided. instead can create function adds click handlers buttons (that's example wrote) , retrieves classes attached element. loops on array of classes , adds every element class one.
$('button').click(function() { var classes = $(this).attr('class').split(' ') classes.foreach(function(elem) { $('.' + elem).addclass('active'); }) })
now if want limit application of said class add element type class should applied before .
$('button.' + elem).addclass('active');
or
$('div.' + elem).addclass('active');
Comments
Post a Comment