-
[100DaysOfCode] 34강Front-end/100DaysOfCode 2022. 9. 12. 12:43
JavaScript HTML DOM
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
HTML DOM(Document Object Model) Tree DOM 드릴링 & 텍스트 노드
첫 번째 자식은 h1 태그가 아니라 text다 🔥 HTML 컨텐츠는 HTML 요소뿐만 아니라 텍스트, 텍스트 조각들도 DOM에 저장된다
🔥 노드와 자식 노드들로 둘 다 접근 가능하고, {children}으로는 저장된 HTML 문서로만 접근 가능하다
🔥 첫 번째 자식은 첫 번째 자식 노드에 액세스 할 수 있다
DOM의 body 안에 있는 첫 번째 자식 노드
DOM 드릴링 제한
만약 새로운 코드를 추가하면
에러가 발생한다
왜?
인덱스 순서가 바꼈는데 children[1]의 <p>태그 단일 요소에서 .href를 찾고 있기 때문이다
DOM에서 요소 검색하기
💡 id로 요소에 접근할 수 있는 문서 객체의 메서드가 있다!
1️⃣ document.getElementById('id 이름');
let anchor = document.getElementById("external-link"); anchor.href = "http://naver.com";
2️⃣ document.querySelector('CSS 선택자');
anchor = document.querySelector("p a"); anchor.href = "http://google.com";
CSS 선택자에 일치하는 첫번째 요소를 반환하는 메서드이다(일치하는 모든 요소를 반환하는 것은 querySelectorAll)
Practice Code
// Exercise Time! // 1. Select the <h1> element by "drilling into the DOM" and // save it in a variable with a name of your choice let selector = document.body.children[0]; selector = document.body.firstElementChild; console.dir(selector); // 2. Use the variable from (1) and get access to the "parent" // element of the stored <h1> element (i.e. to the <body> element) console.dir(selector.parentElement); // BONUS: Try using the variable from (1) to get access to the // sibling element (i.e. the <p> element next to the <h1> element) console.dir(selector.nextElementSibling); // 3. Select the <h1> element with getElementById and store in // the same or a new variable (up to you) selector = document.getElementById("greeting"); console.dir(selector); // 4. Select the second <p> element with querySelector (you might // need to add something in the HTML code, e.g. a class) // and store it in a new variable with a name of your choice let querySel = document.querySelector("span p"); // 5. BONUS TASK: Try changing the text content of the <p> element // you selected in (4) and set it to any other text of your choice // querySel = "I'm Alive!"; (X) querySel.textContent = "I'm Alive!";
'Front-end > 100DaysOfCode' 카테고리의 다른 글
[100DaysOfCode] 35강 (0) 2022.09.14 [100DaysOfCode] 33강 (0) 2022.09.04 [100DaysOfCode] 32강 (0) 2022.09.01 [100DaysOfCode] 31강 (0) 2022.08.26 [100DaysOfCode] 30강 (0) 2022.08.23