#TIL (May 13th, 스물여덟번째 이야기)

Jung Hyun Kim·2020년 5월 12일
0

Javascript DOM

JS In the Browser - DOM(Document Object Model) Manipulation

Introduction to the DOM

-The DOM is a Javascript representation of a webpage

  • It's your JS "WINDOW" into the contents of the webpage

  • It's just a bunch of objects that you can interact with va JS

    =>Document is our entry point!
    document.sth~으로 진행됨!

    Selecting

getElementById

document.getElementById('ddd') 

getElementsByTagName

document.getElementByTagName('input')

getElementsByClassName

document.getElementsByClassName('header')

querySelector

('ddd'). ('#ddd') ('.ddd')

Twisting the DOM to Our Will

innerText/.textContent

  • .innerText는 해당 select한 요소의 보여지는 text만 보여준다면
  • .textContent는 보여지진 않지만 그안에 들어있는 모든 text 요소를 보여줌
    예를 들어 아래 html 페이지에서 웹페이지에 보여지는 단어는
<p id='main'> blah blah 
    <b style="display: none">hahahhahah</b>

    <script>console.log('hello')</script>
</p>
const p= document.querySelector('p');
p.innerText 
// 이렇게 출력됨 "blah blah"
p.textContent
  /*" blah blah 
    hahahhahah

    console.log('hello')
"이렇게 다 출력됨 */

innerHTML

  • HTML element를 더할수 있음!
    예를들어
const h1= document.querySelector('h1')
h1.innerText
"My WebPage"//이렇게 출력이 되는데 여기에 

h1.innerHTML +=' IS COOL'//뒤에 is cool을 더하면 
"My WebPage IS COOL"//이렇게 같이 출력되고 

h1.innerHTML += '<b>hahahahahaha</b>'//안에 볼드체된 요소를 넣으면
"My WebPage IS COOL<b>hahahahahaha</b>"//또한 같이 적용되서 변경된다 

h1.innerText +='<b>awesome</b>'// 예를 들어 innerText도 뒤에 추가하는건 가능하지만 저렇게 하면 글자안에 <b>태그 까지 다같이 보여짐 

"My WebPage IS COOLhahahahahaha<b>awesome</b>"

value, href, src

-HTML 안의 텍스트를 바꾸듯, value나 이미지, 링크들도 변경할 수 있다.

    <input type="password" placeholder="password">
    <input type ="checkbox">

여기서

const inputs = document.querySelectorAll('inputs')
inputs[0].value //하면 password 입력된 값을 볼수 있고
inputs[0].value = 'put your password'
//이렇게 입력 하면 빈칸에 put your password가 출력 됨 

href태그또한 수정 가능하다
<a href="https://www.notion.so/">westudy</a>
const a =document.querySelector('a')
a.href ="https://www.google.com"//이렇게 바꾸어 주면 바꾼디. 

이미지 src도 같은방법으로 수정 가능하다
<img id="my-photo" src="happyme.jpg" alt="joanne photo">
const img=document.querySelector('img')
img.src="ddddddd"
//이렇게 하면 이미지가 수정한걸로 바뀐다

Getting and setting attributes

    <input type ="range" min="100" max="500">

const range = document.querySelector('input[type="range"]')
range.getAttribute('max')
//설정된 "500"이 출력되고
range.getAttribute('min')
//하면 100이 출력되는데.. 여기에
range.setAttribute('min','-100')
//이렇게 하면 min 이 '-100'로 나옴
range.setAttribute('type','radio')
//이렇게 하면 range 인 input type이 아예 라디오 형태로 바뀐다 

Finding parent/children/sibilings

.parentElement

const firstLi=document.querySelector('li')
firstLi.parentElement 
//하면<ul>..</ul> 이 출력되고 여기에
firstLi.parentElement.parentElement
//<body>...</body> 이렇게 순서가 올라간다..

.children

const ul=document.querySelector('ul')
ul.children // 이렇게 하면 아래 있는 li가 출력된다.
ul.children[0] // 이러면 첫번째 li가 출력됨 

.nextElementSibling

firstLi.nextElementSibling
//이러면 두번째 li element가 나옴 

getComputedStyle

const li=document.querySelector('li')//이렇게 하고
const styles= getComputedStyle(li)
//styles를 출력하면 여러 요소들이 나옴 
styles.color = 'red'
//이러면 스타일이 바뀜 

Manipulating class

const todo120 = document.querySelector(".todo2");

todo120.style.color ='gray';
todo120.style.textDecoration = 'line-through';
todo120.style.opacity ='50%';
//이런식으로 하면 css style을 바꿀수 있음 혹은 

todo120.setAttribute('class','done') 
//이런식으로 적용도 가능하다! 그렇기 때문에 classlist가 나옴

.classlist

todo120.classList //이렇게 하면 todo120 에 있는 모든 효과를 볼수 있음.
//그렇게 하고 이렇게 입혀진 클래스를 없앨수도 있음
todo120.classList.remove('done')
todo120.classList.add('done')
//더 할수도 있음 
todo120.classList.toggle('done')
//이렇게 하면 없으면 있고, 있으면 없게끔 효과 줄수 있음 

Creating element

.appendChild()

const newImg = document.createElement('img');
newImg.src='https://images.unsplash.com/photo-1589289066046-626c1a4a8cdf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=668&q=80';
newImg.style.width="300px";
document.body.appendChild(newImg);

const newLink = document.createElement('a');
newLink.innerText= 'Mr Bix. video! click me';
newLink.href='http://www.youtube.com';

const firstP=document.querySelector('p');
firstP.appendChild(newLink);

.insertBefore()

.insertBefore(무엇을,어디에) 
const parentUL = document.querySelector('ul');
const newLI = document.createElement('li');
newLI.innerText = 'I am a new Li';
parentUL.appendChild(newLI)
//이렇게 하면 newLI는 LI중 제일 위에 들어가게 된다

const firstLI = document.querySelector('li.todo')
parentUL.insertBefore(newLI,firstLI)

//이렇게 해도 newLI는 LI중 가장 위에 위치하게된다
Const lastUL = document.querySelectorAll('li.todo')[2]

parentUL.insertBefore(newLI,lastUL) //하면 리스트의 제일마지막 위에 위치하게된다 

firstP1.insertAdjacentElement('beforebegin', I)
//이런방법도있음 
.append(무엇을,여기에) //이렇게 하면 여기에의 뒤에
.prepend(무엇을,여기에) // 여기의 앞에 

.removeChild

const removeMe=ul.querySelector('.special')
ul.removeChild(removeMe) //무엇을 어디에서 없앨것인가

const deleted =ul.removeChild(removeMe)
//하면 removed된것을 가져올수 있음 

.remove()

const h1= document.querySelector('h1')
h1.remove()//하면 그냥 사라짐, parent필요없음 
profile
코린이 프론트엔드 개발자💻💛🤙🏼

0개의 댓글