문제:
[JavaScript] (해결) 동적으로 font awesome 아이콘 추가하기
나는 쇼핑목록 앱을 만들고있다. TO DO LIST처럼 쇼핑할 물건들을 적는 리스트이다. 현재 문제점 : appendChild, innerHTML 등을 이용하여 font awesome icon을 추가하려한다. 이런식으로. 다만 x 표시(빨간색
breathtaking-life.tistory.com
Event binding on dynamically created elements?
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off. This happens on page re...
stackoverflow.com
결국 스택오버플로우에 글을 올렸다.
그리고 몇분 뒤 빠르게 답이 왔다.
(소스 파일 전체는 링크 안에 있다.)
document.querySelector(".deco").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("fa-trash")) tgt.closest("li").remove();
})
처음 안 사실: closest라는 메소드가 있다.
뒤늦게 알게 되었는데 jquery 메소드다...
Element.closest() - Web APIs | MDN
The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.var close
developer.mozilla.org
설명 : 기준 Element 에서부터 closest() 메소드를 통해 자신부터 부모 요소 단위로 출발하여 각 요소가 지정한 선택자에 만족할 때까지 탐색한다(문서 루트까지 이동). 이 중 가장 가깝게 조건에 만족한 부모 요소가 반환되며, 조건에 만족한 요소가 없으면 null 값을 반환한다.
'IT > JavaScript' 카테고리의 다른 글
[자바스크립트]객체 문자열 변환 JSON stringify, parse (0) | 2021.01.06 |
---|---|
[자바스크립트] 버블링과 캡쳐링 (0) | 2021.01.05 |
[JavaScript] (해결) 동적으로 font awesome 아이콘 추가하기 (2) | 2021.01.04 |
[JavaScript] 렌더링 트리(Critical Rendering Tree) (0) | 2021.01.03 |
[JavaScript] clientX/Y, pageX/Y, MouseEvent (0) | 2021.01.01 |