<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>03-dom-sort.html</title>
<style>
table {
border: 2px solid black;
border-collapse: collapse;
}
td, th {
padding: 10px;
border: 1px solid grey;
}
thead {
background-color: #dadada;
}
thead > tr > th:hover {
cursor: pointer;
background-color: black;
color: white;
}
</style>
</head>
<body>
<h1>03-dom-sort.html</h1>
<hr>
<table>
<thead>
<tr>
<th>이름</th>
<th>나이</th>
</tr>
</thead>
<tbody>
<tr>
<td>짱구</td>
<td>8</td>
</tr>
<tr>
<td>훈이</td>
<td>5</td>
</tr>
<tr>
<td>철수</td>
<td>9</td>
</tr>
<tr>
<td>유리</td>
<td>7</td>
</tr>
<tr>
<td>맹구</td>
<td>10</td>
</tr>
<tr>
<td>흰둥이</td>
<td>6</td>
</tr>
</tbody>
</table>
<script>
const ageTh = document.querySelector('thead > tr > th:nth-child(2)')
function sortByAge() {
const trList = document.querySelectorAll('tbody > tr')
const trArray = Array.from(trList)
trArray.sort((a, b) => {
const ageA = +a.querySelector('td:nth-child(2)').innerText
const ageB = +b.querySelector('td:nth-child(2)').innerText
return ageA > ageB ? 1 : -1
})
const tbody = document.querySelector('tbody')
trArray.forEach(tr => tbody.appendChild(tr))
}
ageTh.onclick = sortByAge
const nameTh = document.querySelector('thead > tr > th:nth-child(1)')
function sortByName() {
const trArr = Array.from(document.querySelectorAll('tbody > tr'))
trArr.sort((a, b) => {
const nameA = a.querySelector('td').innerText
const nameB = b.querySelector('td').innerText
return nameA > nameB ? 1 : -1
})
const tbody = document.querySelector('tbody')
trArr.forEach(tr => tbody.appendChild(tr))
}
nameTh.onclick = sortByName
</script>
</body>
</html>