How to select the last row of a table using jQuery ?
Given an HTML table and the task is to select the last row of the table with the help of jQuery. There are two approaches that are discussed below with the proper example.
Approach 1: First, select the table by its ID. Use find() method to find the all table rows of the table. Use last() method to get the last row of table. The background color of the last element has been changed to see the effect.
-
Example:
<!DOCTYPE HTML>
<
html
>
<
head
>
<
title
>
How to select the last row of
a table using jQuery?
</
title
>
<
script
src
=
</
script
>
<
style
>
h1 {
color: green;
}
</
style
>
</
head
>
<
body
>
<
center
>
<
h1
>
GeeksforGeeks
</
h1
>
<
b
>
Click on the button to select last
item of table
</
b
>
<
table
>
<
tr
>
<
th
>Sl.No</
th
>
<
th
>Title</
th
>
<
th
>Geek_id</
th
>
</
tr
>
<
tr
>
<
td
>01</
td
>
<
td
>HTML</
td
>
<
td
>Markup Language</
td
>
</
tr
>
<
tr
>
<
td
>02</
td
>
<
td
>CSS</
td
>
<
td
>Cascading Style</
td
>
</
tr
>
<
tr
>
<
td
>03</
td
>
<
td
>JavaScript</
td
>
<
td
>Scripting Language</
td
>
</
tr
>
<
tr
>
<
td
>04</
td
>
<
td
>Bootstrap</
td
>
<
td
>Framework</
td
>
</
tr
>
</
table
>
<
br
>
<
button
onclick
=
"Geeks()"
>
Click here
</
button
>
</
center
>
<
script
>
function Geeks() {
$('table tr:last')
.css("background-color", "yellow");
}
</
script
>
</
center
>
</
body
>
</
html
>
- Output:
Approach 2: Use $(‘table tr:last’) jQuery Selector to find the last element of the table. The ‘table’ in query looks for the table element then ‘tr’ is looking for all the rows in the table element and ‘:last’ is looking for the last table row of the table.
-
Example:
<!DOCTYPE HTML>
<
html
>
<
head
>
<
title
>
How to select the last row of
a table using jQuery?
</
title
>
<
script
src
=
</
script
>
<
style
>
h1 {
color: green;
}
</
style
>
</
head
>
<
body
>
<
center
>
<
h1
>
GeeksforGeeks
</
h1
>
<
b
>
Click on the button to select last
item of table
</
b
>
<
table
>
<
tr
>
<
th
>Sl.No</
th
>
<
th
>Title</
th
>
<
th
>Geek_id</
th
>
</
tr
>
<
tr
>
<
td
>01</
td
>
<
td
>HTML</
td
>
<
td
>Markup Language</
td
>
</
tr
>
<
tr
>
<
td
>02</
td
>
<
td
>CSS</
td
>
<
td
>Cascading Style</
td
>
</
tr
>
<
tr
>
<
td
>03</
td
>
<
td
>JavaScript</
td
>
<
td
>Scripting Language</
td
>
</
tr
>
<
tr
>
<
td
>04</
td
>
<
td
>Bootstrap</
td
>
<
td
>Framework</
td
>
</
tr
>
</
table
>
<
br
>
<
button
onclick
=
"Geeks()"
>
Click here
</
button
>
</
center
>
<
script
>
function Geeks() {
$('table tr:last')
.css("background-color", "yellow");
}
</
script
>
</
center
>
</
body
>
</
html
>
- Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of
“Write less, do more”
.
You can learn jQuery from the ground up by following this
jQuery Tutorial
and
jQuery Examples
.
Please Login to comment...