2019年鐵人賽
、 JS
範例
<div class="main">
<div class="coffee">coffee</div>
<div class="milk">milk</div>
<div class="water">water</div>
</div>
JS
//querySelector用css選擇器的寫法找到相對應的節點,例如要找id就用('#id_name')放入字串中
let main = document.querySelector('.main');
console.log(main);
//找到類陣列NodeList
let divLists = document.querySelectorAll('div');
console.log(divLists);
let divTag = document.createElement('div');
console.log(divTag);
let divText = document.createTextNode('Hello World!');//創建文字節點
console.log(divText);
先把上面創建的 li 文字節點添加到 li 節點裡,再把 li 節點添加到 ul 節點裡。
liTag.appendChild(liText);
ulTea.appendChild(liTag);
console.log(ulTea);
範例
<ul class="tea">
<li>blacktea</li>
</ul>
複製節點,參數給布林值, true 的話連子節點都一起複製
let ulTea = document.querySelector('.tea');
let newUlTea = ulTea.cloneNode(true);
console.log(newUlTea);
false 的話,只複製該節點。
let ulTea = document.querySelector('.tea');
let newUlTea = ulTea.cloneNode(false);
console.log(newUlTea);
範例
<div class="main">
<div class="coffee">coffee</div>
<div class="milk">milk</div>
<div class="water">water</div>
</div>
對父節點下 removeChild,參數為想要刪除的子節點
let main = document.querySelector('.main');
let coffee = document.querySelector('.coffee');
main.removeChild(coffee);
console.log(main);