ใช้ jQuery Selector :last เข้าถึง element สุดท้ายโดยตรง
ไม่ต้องใช้ length ใช้ selector 'table tr:last td' เลือก td ของแถวสุดท้ายทันที
ตัวอย่างโค้ดเต็ม
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Last Item</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<table id="demo" border="1">
<tr><td>John</td></tr>
<tr><td>David</td></tr>
<tr><td>Mike</td></tr>
</table>
<script>
var lastValue = $('table tr:last td').text();
console.log("The last value is = " + lastValue); // Mike
</script>
</body>
</html>
วิธีรัน
บันทึกเป็น index.html แล้วเปิดด้วย Live Server
วิธี Vanilla JS (ไม่ใช้ jQuery)
// querySelector รองรับ :last-child
const lastTd = document.querySelector('table tr:last-child td');
console.log(lastTd.textContent); // Mike
// หรือใช้ NodeList + spread
const rows = document.querySelectorAll('table tr');
const lastRow = [...rows].pop();
console.log(lastRow.querySelector('td').textContent);
คำอธิบาย
- jQuery
:lastselector เลือก element ตัวสุดท้ายในชุด - Vanilla JS ใช้
:last-childpseudo-class - ไม่ต้องคำนวณ length หรือ index เอง