Mehrshad Farahani Mehrshad Farahani - 7 months ago 56
Javascript Question

Simulate click on same div by class names

I have five boxes with the same class name but some

<div>
s has another class too.
Example:

<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
.test
class but it clicks on all boxes:

$('.test').click();


How can I simulate click on the second
<div>
that only has
.test
class name, and not more?

Answer

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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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