HTML:
<section id="section6">
<h1>Ex6-노드조작: 메뉴추가(createTextNode, Element) </h1>
<div>
<input class="title-input" name="title">
<input type="button" class="add-button" value="추가하기">
<input type="button" class="del-button" value="삭제하기">
</div>
<ul class="menu-list">
<li><a href="">aaa</a></li>
<li><a href="">bbb</a></li>
</ul>
</section>
JavaScript:
//Ex6 :
window.addEventListener("load", function () {
var section = document.querySelector("#section6");
var titleInput = section.querySelector(".title-input");
var menuListUl = section.querySelector(".menu-list")
var addButton = section.querySelector(".add-button");
var delButton = section.querySelector(".del-button");
addButton.onclick = function () {
var title = titleInput.value;
var html = '<a href="">'+ title +'</a>';
//태그안에 title을 저장하는 방법
var li = document.createElement("li");
li.innerHTML = html;//<a>안의 title을 <li>로 감싸기.
menuListUl.append(li);
};
delButton.onclick = function () {
// var txtNode = menuListDiv.childNodes[0]
// menuListUl.removeChild(txtNode); 부모를 사용한 삭제.
var liNode = menuListUl.children[0]; //스스로를 삭제.
liNode.remove();
};
});
결과: 잘 동작함!