문제
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.getElementById()는 주어진 문자열과 일치하는 id 속성을 가진 요소를 찾고, 이를 나타내는 엘리먼트 객체를 반환한다. ID는 문서 내에서 유일해야 하기 때문에 특정 요소를 빠르게 찾을 때 유용하다.
document.getElementById(id);
innerHTML은 엘리먼트 내에 포함된 HTML 또는 XML 마크업을 가져오거나 설정한다.
// 문서(document)의 body 속성(attribute)을 지우면, 문서의 전체 내용을 지울 수 있다
document.body.innerHTML = "";
tagName 읽기 전용 속성은 요소에 호출된 태그명을 가져온다. 예를 들면, 만약 <img> 요소일 경우, 해당 요소의 tagName 속성의 내용은 "IMG"가 된다(이것은 HTML인 경우에 대한 내용이고, XML / XHTML 문서에서는 대소문자가 다르게 나올 수 있다).
return e.target.tagName === "DIV" ? "div" : "others"
정답
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="description" content="Webpage description goes here" />
<meta charset="utf-8" />
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="list-app"></div>
<script>
const app = document.getElementById("list-app");
// ul 엘리먼트를 생성해 list 변수에 할당한다
// input 엘리먼트를 생성해 텍스트 입력을 위한 input 변수에 할당한다
// input 요소의 type 속성을 "text"로 설정한다
// button 엘리먼트를 생성한다
// "추가"라는 텍스트를 가진 버튼을 나타내는 addButton 변수에 할당한다
const list = document.createElement("ul");
const input = document.createElement("input");
input.setAttribute("type", "text");
const addButton = document.createElement("button");
addButton.innerHTML = "추가";
// addButton 요소에 클릭 이벤트 리스너를 추가한다
// 버튼을 클릭하면 새로운 li 엘리먼트를 생성한다 newItem 변수에 할당한다
// newItem의 엘리먼트 내용을 input 요소의 값으로 설정한다
// newItem을 list에 추가한다
addButton.addEventListener("click", () => {
const newItem = document.createElement("li");
newItem.innerHTML = input.value;
list.appendChild(newItem);
input.value = "";
});
// list 요소에 클릭 이벤트 리스너를 추가한다
// 클릭된 요소의 태그 이름이 li이면 사용자에게 새로운 텍스트를 입력받는 프롬프트 창을 표시한다
// 입력받은 텍스트로 클릭된 li 요소의 내용을 변경한다
list.addEventListener("click", e => {
if (e.target.tagName === "LI") {
const text = prompt("새로운 텍스트를 입력해주세요:");
e.target.innerHTML = text;
}
});
// list, input, addButton 요소를 app 요소에 추가해 페이지에 표시한다
app.appendChild(list);
app.appendChild(input);
app.appendChild(addButton);
</script>
</body>
</html>