even() and odd() in JQuery

Introduction:

  JQuery came up with a new methods even() and odd() to replace its  complex selectors :even and :odd from its latest release version 3.5.0. To be noted still the jQuery extends its support for the selector :even and :odd in it’s latest release.

:even and :odd

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script>
$(document).ready(function(){
  $("tr:even").css("background-color", "yellow");
  $("tr:odd").css("background-color", "grey");
 
});
</script>
</head>
<body>

<h4>JQuery 3.5.0 </h4>
<table border="1">
  <tr>
    <th>EmpID</th>
    <th>Emp</th>
  </tr>
  <tr>
      <td>1</td>
    <td>Arun</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Govind</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Gowtham</td>
  </tr>

</table>

</body>
</html>

From the above code you can observe two things,

  1. We have used JQuery CDN V3.5.0 which is latest
  2. Still it supports: even and: odd selectors
Figure 1: Using :even and :odd selectos

Now let’s replace: even and: odd selector to even() and odd() respectively

even() and odd()

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script>
$(document).ready(function(){
 $("tr").even().css("background-color", "yellow");
  $("tr").odd().css("background-color", "grey");
});
</script>
</head>
<body>

<h4>JQuery 3.5.0 </h4>
<table border="1">
  <tr>
    <th>EmpID</th>
    <th>Emp</th>
  </tr>
  <tr>
      <td>1</td>
    <td>Arun</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Govind</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Gowtham</td>
  </tr>

</table>

</body>
</html>

Based on code the yellow color is applied to the even rows and grey color is applied to the odd rows in the table.

Figure 2: Using odd() and even()

Summary:

We have seen how to use the even() and odd() methods in Jquery which is released with it’s latest version v3.5.0.

I hope you have enjoyed this blog. Your valuable feedback, questions, or comments about this blog are always welcomed.

Happy Coding!!!

gowthamk91

Leave a Reply

%d