Home » Jquery » javascript – jQuery How to add click to ul-Exceptionshub

javascript – jQuery How to add click to ul-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I want to add class checked on li when users click it using jQuery. I have written the below code which works.

HTML

<ul>
    <li class="row">Documents checked</li>
    <li class="row">Documents Verified </li>
    <li class="row">Forwarded to Logistics </li>
    <li class="row">Received by Logistics</li>
</ul>
.checked {
  background: green;
}

jQuery

$(function() {
    $('li.row').on('click', function() {
      $(this).addClass('checked');
    });
});

This is working but I am told this is bad practice and asked to find better way to do this. I do the following but it is not working.

$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});
How to&Answer:
$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});

it’s wrong because you cant select li by click on you ul
if you want to add class or delete class with click you can use (toggleClass) like this

$('li').find(.row).on('click', function() {
      $(this).toggleClass('checked');
    });

but if you want to just add class write like this

$('li').find(.row).on('click', function() {
          $(this).addClass('checked');
        });

Answer:

use this Code for solution your problem

$(".row").click(function(){
  $(this).toggleClass("change")
})
.change {
  background-color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li class="row">Documents checked</li>
    <li class="row">Documents Verified </li>
    <li class="row">Forwarded to Logistics </li>
    <li class="row">Received by Logistics</li>
</ul>