JS

JS 40-1 getElement, querySelector로 요소 검색하기 1

와라리요 2023. 1. 10. 14:07

getElementById

 - 요소에 id 속성이 있으면 위치에 상관없이 메서드 document.getElementById(Id)를 이용해 id 값을 들고 있는 테그에 접근할 수 있다.

<h1 id="title">제목</h1>

<script>
	// 요소 접근
    let title = document.getElementById('title');
    // 제목 -> 자바스크립트를 공부하자!!로 변경됨.
    title.innerText = "자바스크립트를 공부하자!!";
</script>

 

  id 속성값을 그대로 딴 전역 변수를 이용해 접근할 수도 있다.

<h1 id="title">제목</h1>

<script>
    // 요소 접근 제목 -> 자바스크립트를 공부하자!!로 변경됨.
    title.innerText = "자바스크립트를 공부하자!!";
</script>

 

  그런데 이렇게 요소 id를 따서 자동으로 선언된 전역변수는 동일한 이름을 가진 변수가 선언되면 무용지물이 된다.

<h1 id="title">제목</h1>

<script>
    let title = "바뀌지 않음";
    
    title.innerText = "자바스크립트를 공부하자!!";
    
    console.log(title); // '바뀌지 않음'이 콘솔창에 나옴.
</script>

 

  위와 같은 이유로 id를 전역변수로 사용해서 하는 것은 많이 위험하다. 그래서 document.getElementById('Id')를 사용할 것!!

 

 


querySelecterAll

  document.querySelectorAll(css) 메소드는 자식 요소 중 css 선택자에 대응하는 요소를 모두 반환한다. 그렇기 때문에 황용도 높다!!

 

예(퍼옴)

<ul>
  <li>1-1</li>
  <li>1-2</li>
</ul>
<ul>
  <li>2-1</li>
  <li>2-2</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "1-2", "2-2"
  }
</script>

 

  가상 클래스도 사용할 수 있다. :hover, :active와 같은 css 선택자의 가상 클래스도 사용할 수 있다. document.querySelectorAll(':hover')을 사용하면 ':hover' 상태인 요소 모드를 담은 컬렉션이 반환된다. 이때 컬렉션은 DOM 트리 최상단(<html>)부터 가장 하단의 요소 순으로 채워진다.

 


querySelecter

  elem.querySelector(css)는 주어진 CSS 선택자에 대응하는 요소 중 첫 번째 요소를 반환한다.

  elem.querySelectorAll(css)[0]과 동일하죠. elem.querySelectorAll(css)[0]은 선택자에 해당하는 모든 요소를 검색해 첫 번째 요소만을 반환하고, elem.querySelector는 해당하는 요소를 찾으면 검색을 멈춘다는 점에서 차이가 있다. 

 


공부한 곳!! 모던 JavaScript 튜토리얼