搜尋元素
重要性:4
以下是包含表格和表單的文件。
如何尋找…?
- 具有
id="age-table"
的表格。 - 該表格內的所有
label
元素(應有 3 個)。 - 該表格中的第一個
td
(帶有字詞「年齡」)。 name="search"
的form
。- 該表單中的第一個
input
。 - 該表單中的最後一個
input
。
在一個獨立的視窗中開啟頁面 table.html 並使用瀏覽器工具。
有很多方法可以做到這一點。
以下是其中一些方法
// 1. The table with `id="age-table"`.
let table = document.getElementById('age-table')
// 2. All label elements inside that table
table.getElementsByTagName('label')
// or
document.querySelectorAll('#age-table label')
// 3. The first td in that table (with the word "Age")
table.rows[0].cells[0]
// or
table.getElementsByTagName('td')[0]
// or
table.querySelector('td')
// 4. The form with the name "search"
// assuming there's only one element with name="search" in the document
let form = document.getElementsByName('search')[0]
// or, form specifically
document.querySelector('form[name="search"]')
// 5. The first input in that form.
form.getElementsByTagName('input')[0]
// or
form.querySelector('input')
// 6. The last input in that form
let inputs = form.querySelectorAll('input') // find all inputs
inputs[inputs.length-1] // take the last one