<div id="nulbo">늘보<div>
위와 같은 객체를
let t = document.getElementById("nulbo");
t.addEventListener("click", function(event){
alert("안녕 늘보");
});
마우스로 클릭했을 때 이벤트가 일어나는 event target으로 지정해주었다.
console.log(event.target.tagName); // div
console.log(event.target.id); // nulbo
console.log(event.target.textContent); // 늘보
이 밖에도 다양한 속성 값을 얻을 수 있다.
<table>
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong><br>Metal<br>Silver<br>Elders</td>
<td class="n">...</td>
<td class="ne">...</td>
</tr>
<tr>...2 more lines of this kind...</tr>
<tr>...2 more lines of this kind...</tr>
</table>
위와 같이 9개의 칸이 있는 테이블이 있을 때
table 요소.onclick = function(event) {
// TD에서 발생한 게 아니라면 아무 작업도 하지 않는다,
if (event.target.tagName != 'TD') return;
console.log(event.target.textContent); // event target의 텍스트를 출력한다.
};
각 <td>
마다 onclick
핸들러를 할당하는 대신 <table>
요소에 할당하여 원하는 동작을 구현할 수 있다.
<td>
<strong>Northwest</strong>
...
</td>
하지만 <td>
안에 중첩 태그 <strong>
이 있어 버그가 발생할 수 있다.
var closestElement = targetElement.closest(*selectors*);
closest 메소드를 이용하여 중첩 태그 <strong>
이 선택되더라도 <td>
를 찾을 수 있다.
table.onclick = function(event) {
let td = event.target.closest('td');
if (!td) return;
if (!table.contains(td)) return;
console.log(event.target.textContent);
};