allows js to access and manipulate the document and its elements
window.onload = function(){}
안에 코드 작성document.getElementById("아이디속성값");
document.getElementsByTagName("태그명");
document.getElementsByName("name속성값");
document.getElementsByClassName("class속성값");
document.querySelector("선택자");
'div'
, (id)'#id'
, (class)'.className'
document.querySelectorAll("선택자명");
console.dir(document.body)
console.dir(document.body.children)
let newsContents = document.body.children[1];
console.dir(newsContents);
//get parent element
console.log(newsContents.parentElement);
//put all the div elements in an array
//iterate through all array elements and print out the div's classname
let divList = document.getElementsByTagName('div');
for (let div of divList) console.log(div.className);
let navElement = document.getElementById('nav');
consoleLogAllElement(navElement);
function consoleLogAllElement(elem){
console.log(elem.id || elem.className);
let printAllElements = function(el){
if (el.children.length){
for (let child of el.children) console.log("Child of " + (el.id || el.className) + ": " + child.className);
for (let child of el.children) printAllElements(child);
}
}
printAllElements(elem);
}
//access
const oneDiv = document.createElement('div');
const container = document.querySelector('#container');
//update
oneDiv.textContent = 'dev';
oneDiv.classList.add('any text');
//setAttribute: element.setAttribute( 'attributename', 'attributevalue' )
oneDiv.setAttribute('title', 'This is the title');
//append
container.append(oneDiv);
//delete one element
oneDiv.remove();
//delete many elements
//security risk- do not use innerHTML!
//document.querySelector('#container').innerHTML = '';
//more securely..
const container = document.querySelector('#container');
while (container.firstChild) {
container.removeChild(container.firstChild);
}
const container = document.querySelector('#container');
while (container.children.length > 1) {
container.removeChild(container.lastChild);
}
//remove all of a certain clsss
const tweets = document.querySelectorAll('.tweet')
tweets.forEach(function(tweet){
tweet.remove();
})
// or
for (let tweet of tweets){
tweet.remove()
}
Q. 생성한 tweetDiv 를 container 에 넣기 위해서는, container 를 먼저 찾아야 합니다. 어떻게 container 를 찾을 수 있을까요? 위에서 언급했던 DOM 트리를 순회해서 찾을 수 있습니다. 그러나 보다 더 편리한 방법이 있으니 검색해 보시기 바랍니다.
innerHTML
renders complete markup rather than just text - which means malicious code can be injected into your site and then executed (XSS attack)
The website can become very vulnerable if innerHTML is used constantly. For instance, using it for input fields can cause DOM manipulation, and attackers can use cross-site scripting (XSS) to insert harmful scripts and steal the private and sensitive data stored in session cookies.
심화 학습 목표