문제
JavaScript DOM - Code Exercises | CroCoder
The DOM or the Document Object Model of the page is created after the web page is loaded. Learn some DOM manuipulation with these exercises.
www.crocoder.dev
메모
- Document.querySelector()는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element를 반환한다. 일치하는 요소가 없으면 null을 반환한다.
- Document.createElement()는 지정한 tagName의 HTML 요소를 만들어 반환한다. tagName을 인식할 수 없으면 HTMLUnknownElement를 대신 반환한다.
- Node.appendChild()는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙인다. 만약 주어진 노드가 이미 문서에 존재하는 노드를 참조하고 있다면 appendChild()는 노드를 현재 위치에서 새로운 위치로 이동시킨다. 문서에 존재하는 노드를 다른 곳으로 붙이기 전에 부모 노드로부터 지워버릴 필요는 없다.
정답
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<div></div>
<div>ddd</div>
<script>
// imageSrc는 <div> 태그에 삽입하려는 이미지 경로를 설정한다
const imageSrc = "https://crocoder.dev/icon.png";
// divElement는 HTML 문서의 첫 번째 <div> 태그를 선택자로 반환한다
const divElement = document.querySelector("div");
// imgElement는 <img> 태그를 생성한다
const imgElement = document.createElement("img");
// imgElement의 src(이미지 경로)는 imageSrc이다
imgElement.src = imageSrc;
// divElement의 자식 요소로 imgElement를 삽입한다
divElement.appendChild(imgElement);
</script>
</body>
</html>