Mehrshad Farahani Mehrshad Farahani - 6 months ago 40
Javascript Question

Simulate click on same div by class names

I have five boxes with the same class name but some

s has another class too.

<div class="test one"></div>
<div class="test"></div>
<div class="test two"></div>
<div class="test three"></div>
<div class="test five"></div>

I use this code for clicking on boxes with
class but it clicks on all boxes:


How can I simulate click on the second
that only has
class name, and not more?


You could return all classes with attr and check length

$('.test').click(function() {
  var c = $(this).attr('class').split(' ').length;
  if (c == 1) {
    $(this).css('background', 'blue');
<script src=""></script>
<div class="test one">Lorem ipsum dolor.</div>
<div class="test">Lorem ipsum dolor.</div>
<div class="test two">Lorem ipsum dolor.</div>
<div class="test three">Lorem ipsum dolor.</div>
<div class="test five">Lorem ipsum dolor.</div>

If you always want to target div with only test class no matter which one you click you can do this Fiddle