The Web Developer 부트캠프 2022

JS CSS STYLE, classList, 계층이동, 삭제

거위발바닥 2022. 9. 22. 22:24

CSS STYLE

document.querySelector("#container").style.textAlign = "center";
document.querySelector("img").style.width = "150px";
document.querySelector("img").style.borderRadius = "50%"

위와 같이 querySelector로 id나 tag class등을 잡고 .style.textAlign등을 사용해 css를 줄 수 있다.

하지만 css와 다른점은 css는 text-align 이며 border-radius 이지만 JS는 인라인 - 을 사용하지 않고

모두 카멜케이스를 사용한다. 또한 주는 값도 모두 string 처리를 해야 한다. 

window.getComputedStyle(h1).color
window.getComputedStyle(h1).fontSize

개발자 모드에 해당 값을 코드를 사용함으로써 h1에 사용된 색상이나 폰트사이즈의 값을 쉽게 알아낸다.

 

CLASSLIST

h2.classList.add('purple')
h2.classList.remove('purple')
h2.classList.toggle('purple')

add는 class를 추가하고 remove는 삭제한다.

toggle의 기능은 해당 toggle이 실행되면 true값을 출력하고 한번 더 실행하면 false값을 실행하는 

on off 가 가능한 기능이다. 

 

계층이동

 

// 1
document.body.appendChild(newImg)
const newH3 = document.createElement('h3')
newH3.innerText = "i am new!"

// 2
const p = document.querySelector('p')
p.append(" i am new text!!!!!")

//3
const h2 = document.createElement('h2')
h2.append("are adorable chickens")
const h1 = document.querySelector('h1')
h1.insertAdjacentElement('afterend', h2)

//4
const h3 = document.createElement('h3')
h3.innerText = "i am h3";
h1.after(h3)

1번 코드는 body 태그에 newImg라는 변수의 자식요소를 넣는 코드이다. 

2번 코드는 문서에서 태그 p를 변수 p로 정하고 p의 뒤에 새로운 string을 넣는다.

3번 코드는 빈 h2 요소를 새로 만드는 변수를 만든 후 빈 h2에 새로운 string을 넣고 

       h1 ( target element )의 afterend에 새로 만들어진 h2를 넣는다.

4번 코드는 h1의 뒤 ( after )에 h3를 넣는 코드이다.

위 4가지 코드는 모두 역할이 비슷하므로 상황에 따라서 써준다. 

 

for (let i = 1; i <= 100; i++) {
    const h11 = document.querySelector('#container');
    const newButton = document.createElement('button')
    newButton.innerText = i;
    h11.appendChild(newButton);
}

#container 를 가진 div 뒤에 순서 숫자 ( i ) 를 가진 버튼들을 100개 넣어줌

 

삭제

const firstLi = document.querySelector('li')
const parentUL = firstLi.parentElement
parentUL.removeChild(firstLi)

li 태그를 선택하는 firstLi 변수를 만들고 fristLi.parentElement로 li의 부모인 parentUL 변수를 만든다.

이후 parentUL.removeChild(firstLi) 를 입력하면 firstLi의 요소인 li가 하나 사라진다. 

firstLi.remove()

를 사용하면 부모요소든 뭐든 필요없이 그냥 targetElement ( firstLi ) 를 삭제한다. 

 

'The Web Developer 부트캠프 2022' 카테고리의 다른 글

JS CSS STYLE, classList  (0) 2022.09.23
포켓몬 데모  (0) 2022.09.22
JS DOM 선택  (0) 2022.09.22
JS 배열(array) , 객체(object), 매개변수 분해  (1) 2022.09.21
JS 기본매개변수, 전개, Rest  (1) 2022.09.21