정리
document.documentElement; //access to html
document.head;
document.body;
document.getElementById('id');
document.getElementsByTagName('p'); //return iterate
document.getElementsByClassName('class');
document.querySelectorAll('.link');
document.querySelector('#id');
document.querySelectorAll('h2:nth-of-type(2)'); //choose second h2 tag
document.querySelectorAll('p:nth-of-type(2n)'); //choose even p tags
const pList = document.querySelectorAll('h1');
for(p of pList){
p.style.backgroundColor = "#000";
p.style.fontSize = String(Math.random());
}
pList[0]
pList.length
- getElementsByTagName과 querySelector의 차이
pList1 = document.getElementsByTagName('p');
pList2 = document.querySelector('p');
pList1의 반환값 HTMLCollection, pList2의 반환값 NodeList
브라우저의 p값 변경시, HTMLCollection은 변동이 있지만, NodeList는 변동이 없다. (예외있음)
const red = document.getElementById('red');
red.parentNode //same as red.parentElement;
document.documentElement.parentNode //#document
document.documentElement.parentElement //null, parentElement returns Element like http tag
const ul = document.getElementById('color');
ul.childNodes //NodeList, contains newline
ul.children //HTMLCollection
ul.firstChild //#text
ul.lastChild //#text
ul.firstElementChild //li tag
const blue = document.getElementById('blue');
blue.previousSibling; //#text
blue.nextSibling; //#text
blue.previousElementSibling; //li tag
blue.nextElementSibling; //li tag
- nodeName, nodeType, nodeValue
blue.firstChild; //"Blue"
const textNode = blue.firstChild; //undefined
textNode.nodeName; //'#text'
textNode.nodeType; //3, element number
textNode.nodeValue; //'Blue'
textNode.textContent = 'xxxx' //tag not working
textNode.innerHTML = li tag //working
const newLi = document.createElement('li');
newLi.innerHTML = 'green';
newLi; //li green /li
ul.appendChild(newLi);
ul.insertBefore(newLi, red);
newLi.cloneNode(); //undefined
newLi.cloneNode(true); //'green'
ul.removeChild(id);