본문 바로가기

Web

[Web] DOM요소 조작_Document.querySelector( )

728x90
반응형

Document.querySelector('selectors')

다양한 Selector를 이용해서 DOM의 element를 받아오기 위한 API.

document 에서 Selector와 일치하는 첫번째 element를 리턴한다.

일치하는 element가 없으면 null을 리턴한다.

 

selectors는 하나 이상의 CSS Selector를 string type으로 전달 한다.

유효한 CSS Selector가 아닐 경우 SYNTAX_ERR가 발생한다.

SYNTAX_ERR가 발생 시 Selector의 철자를 잘 입력했는지,

class 선택자는 마침표(.)를, id 선택자는 해쉬(#)를 잘 입력했는지 확인한다.

 

const image = document.querySelector('img')  // Tag name
const image = document.querySelector('.img')  // Class
const image = document.querySelector('#img')  // Id
const image = document.querySelector('img[src="..."]')  // Tag name + attribute

 

Document.querySelectorAll('selectors')

document 에서 Selector와 일치하는 모든 element를 Static NodeList 로 리턴한다.

일치하는 element가 없으면 비어있는 NodeList를 리턴한다.

NodeList는 Array 는 아니지만, 유사배열로 배열에서 사용하는 메소드를 대부분 사용할 수 있다.(ex. forEach())

 

*Static Collection NodeList (정적 콜렉션) DOM이 변경되어도 collection의 내용에는 영향을 주지 않기 때문에 우리가 원하는 대로 조작을 했을 때 예측한 대로 동작한다.

 

Document.querySelector()를 이용한 DOM요소 조작의 예시

<section>
  <h1>Hello!!</h1>
  <h3>...</h3>
</section>

<script>
  const section = document.querySelector('section');
  const h2 = document.createElement('h2');  // <h2>태그를 생성
  h2.setAttribute('class', 'title');  // <h2 class="title"></h2>
  h2.textContent = 'this is a title';  // <h2 class="title">this is a title</h2>
  section.appendChild(h2);  // <section>태그 안에 <h2>태그를 추가
</script>

 

새로운 요소를 만들기 위해서는

createElement()로 새로운 요소 태그를 생성하고,

setAttribute()로 속성 값을, textContent로 text를 입력한다.

그 다음 append() / appendChild()를 이용하여 태그를 추가한다.

이때 section 컨테이너의 제일 끝 부분에 추가하는 것과 같이 동작한다.

만약에 컨테이너 중간에 태그를 추가하고자 할 때는 insertBefore()를 사용한다.

 

parentNode.insertBefore(newNode, referenceNode);

 

<section>
  <h1>Hello!!</h1>
  <h3>...</h3>
</section>

<script>
  const section = document.querySelector('section');
  const h3 = document.querySelector('h3');
  const h2 = document.createElement('h2');  // <h2>태그를 생성
  h2.setAttribute('class', 'title');  // <h2 class="title"></h2>
  h2.textContent = 'this is a title';  // <h2 class="title">this is a title</h2>
  section.insertBefore(h2, h3);  // <section>태그 안에 <h3>태그 전에 <h2>태그를 추가
</script>

 

 

 

 

⭐ 본 포스팅은 개인 공부 목적으로 기록한 글입니다.

728x90
반응형