<ul class="list">
<li>
<input type="text">
<span>123456789</span>
<button type="button">按鈕</button>
</li>
</ul>
// 取得 list 節點
const list = document.querySelector('.list');
const printTxt = document.querySelector('.printTxt');
// 監聽 list 結構
// 分別點選 input, span, button
list.addEventListener('click', (e)=>{
console.log(e.target);
// 顯示 input, span, button 的標籤
console.log(e.target.closest("li"));
// 使用 closest li
// 選取到的全部都是從 li 開始抓取
// <li>
// <input type="text">
// <span>123456789</span>
// <button type="button">按鈕</button>
// </li>
console.log(e.target.closest("span"));
// 分別點選 input, span, button
// input, button 因為與 span 屬於同層,非父子層,接回傳 null
})
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.