querySelector
<body>
<h1 class="txt">안녕하세요</h1>
<script>
//문서에 class가 txt인 요소를 header에 저장
const header = document.querySelector('.txt')
console.log(header)
</script>
</body>
출력화면 ==>
querySelectorAll
<body>
<h1 class="txt">헬로</h1>
<h1 class="txt">니하오</h1>
<h1 class="txt">봉주르</h1>
<h1 class="txt">안녕</h1>
<script>
//문서에 class가 txt인 모든 요소를 headers에 저장
const headers = document.querySelectorAll('.txt')
console.log(headers)
</script>
</body>
출력화면 ==>
<body>
<div id="a"></div>
<div id="b"></div>
<script>
const a = document.querySelector('#a')
const b = document.querySelector('#b')
//텍스트 형태로 태그 사이에 넣어준다
a.textContent = '<h1>textContent 속성</h1>'
//태그 형태로 태그 사이에 넣어준다.
b.innerHTML= '<h1>innerHtml 속성</h1>'
</script>
</body>
출력 화면 ==>
querySelector로 지정한 ₩div 태그 안으로 값이 들어간다
setAttribute
<body>
<div class="rect"></div>
<script>
const rect1 = document.querySelector('.rect')
rect1.setAttribute('style', 'border : 1px solid black; width : 100px; height : 100px')
</script>
</body>
출력 화면 ==>
지정한 태그 안에 넣을 속성을 요소.setAttribute('속성명','속성 값') 형식으로 작성
<body>
<div class="box">
첫번째 div
<span class="inner">테스트 입니다.</span>
</div>
<script>
//요소 생성
const header = document.createElement('h1')
console.log(header) //header => <h1></h1>
//문서 안에 body 안에 자식요소로 header(h1태그)를 넣어줌
document.body.appendChild(header)
//querySelector로 가져온 요소에 적용 가능
const box = document.querySelector('.box')
const spanTag = document.querySelector('span')
box.appendChild(header)
//box 안에 span 요소 제거
box.removeChild(spanTag)
</script>
</body>
==> 출력화면
div.box 안에 h1태그가 생성되었다.
- createElement : 문서에 넣을 태그 생성
- appendChild: 문서에 자식요소로 지정한 태그를 넣어줌
- removeChild: appendChild와 반대로 지정한 요소 제거
<body>
<h1>클릭횟수 : 0</h1>
<script>
let counter = 0
const h1 = document.querySelector('h1')
//addEventListener('이벤트 명', '함수')
h1.addEventListener('click', function(){
//클릭 시 실행되길 원하는 코드
counter++
h1.textContent = `클릭횟수 : ${counter} `
})
//removeEventListener('지우고싶은 함수명',콜백 함수)
h1.removeEventListener('click',listener)
</script>
</body>
==> 출력화면
클릭 횟수를 클릭하면 횟수를 1씩 증가시키는 함수
- addEventListener : querySelector로 가져온 요소에 이벤트 설정
- removeEventListener : 설정한 이벤트를 삭제시키는 설정