0

My html is

<tr>
  <td>
    <a id="@td.Id" href="javascript:void(0);" class="details">
      <i class="fal fa-search-plus"></i>
    </a>
   </td>
</tr>

How can i toggle the class from fa-search-plus to fa-search-minus and vice versa

by using the .details click event?

$('#myTable tbody').on('click', '.details', function (e) {
     e.preventDefault();
     var table = $('#myTable').DataTable();
     var tr = $(this).closest('tr');
     var row = table.row(tr);
});

As you may notice, i wish to apply the toggle class on the selected child node and not in the selected one.

OrElse
  • 9,709
  • 39
  • 140
  • 253
  • 2
    `onclick="javascript:void(0);"` not sure why you have that – epascarello May 18 '20 at 13:23
  • So select the element. `$(this).find(i)` and toggle the class – epascarello May 18 '20 at 13:24
  • Note that `onclick="javascript:void(0);"` does precisely nothing but add several bytes to your HTML. `javascript:` is never needed in `onclick` attributes. `void(0)` does nothing when run. If it was `href="javascript:void(0)"` it might make some sense. – Heretic Monkey May 18 '20 at 13:24
  • Also, jQuery has a [`toggleClass`](https://api.jquery.com/toggleClass/) function... – Heretic Monkey May 18 '20 at 13:25
  • Does this answer your question? [Easiest way to toggle 2 classes in jQuery](https://stackoverflow.com/questions/7002039/easiest-way-to-toggle-2-classes-in-jquery) – Heretic Monkey May 18 '20 at 13:27
  • @HereticMonkey Thanks about the onclick event. Actually i cannot see how the other answer applies in my case. Please check the edits – OrElse May 18 '20 at 15:04
  • It is exactly what you are trying to do; toggle two classes on an element, and the accepted answer uses the same technique as the answer you've accepted here. Getting the child node (or descendent node) is also covered in other duplicates. – Heretic Monkey May 18 '20 at 15:07

2 Answers2

4

So select the i and toggle the classes with toggleClass()

$(this).find('i').toggleClass('fa-search-plus fa-search-minus')
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Use $(selector).hasClass(classname) to check if that element has one of the two classes. If so, replace it with the other.

Mason
  • 1,007
  • 1
  • 13
  • 31