개발 소스 중 qeurySelector와 qeurySelectAll이라는 함수가 있길래 궁금해서 검색해보니 getElementById, getElementsByClassName 과 같이 DOM 을 다루는 함수라는 공통점이 있었다. 하지만 꽤 여러가지의 차이점이 있었는데 아래와 같은 차이점이 있었다.
getElementById | querySelector |
id를 가져옴 | class / id 모두 적용 가능하며 class를 사용하여 다수의 element를 가져올 시 가장 상단의 element 하나만 return함 |
속도가 빠름 | 속도가 느림 |
공통적으로 HTML element를 return함 |
getElementsByClassName | querySelectorAll |
HTMLCollection을 리턴 | NodeList를 리턴 |
속도가 빠름 | 속도가 느림 |
HTMLCollection이라 id, name, index로 모두 접근 가능 | index로만 접근 가능 |
for문 가능 | for문 가능 |
List함수의 forEach문이 적용되지 않음 | forEach로 for문 대체 가능 |
아래는 w3school에서 테스트한 결과이다.
<!DOCTYPE html>
<html>
<body>
<h2 class="example">A heading with class="example"</h2>
<p class="example">A paragraph with class="example".</p>
<p class="example1">Click the button to add a background color all elements with class="example".</p>
<p class="example1"><strong>Note:</strong> The querySelectorAll() method is not supported in Internet Explorer 8 and earlier versions.</p>
<p id="example2">querySelector Test</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x, i;
var z;
x = document.querySelectorAll(".example");
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
x.forEach(function(){console.log("1")});
var x1 = document.querySelector(".example"); ==> querySelector는 가장 위에 element만 return
x1.style.backgroundColor = "green";
z = document.getElementsByClassName("example1");
for (i = 0; i < z.length; i++) {
z[i].style.backgroundColor = "yellow";
}
z.forEach(function(){console.log("2")}); ==> z.forEach is not a function
var a, b;
a = document.getElementById('example2');
a.style.backgroundColor = 'blue';
b = document.querySelector('#example2');
b.style.color = 'white';
console.log("querySelectorAll", x); ====> querySelectorAll NodeList(2) [h2.example, p.example]
console.log("getElementsByClassName : ", z); =====> getElementsByClassName : HTMLCollection(2) [p.example1, p.example1]
console.log("getElementById : ", a); ====> getElementById : <p id="example2" style="background-color: blue; color: white;">querySelector Test</p>
console.log("queryselector : ", b); ====> queryselector : <p id="example2" style="background-color: blue; color: white;">querySelector Test</p>
}
</script>
</body>
</html>
'Web > javascript' 카테고리의 다른 글
함수 선언식과 함수 표현식 그리고 화살표 함수 (0) | 2021.08.02 |
---|---|
javascript - strict mode (0) | 2021.07.16 |
콤마 형태의 숫자를 정수형으로 바꾸기 (0) | 2021.04.28 |
javascript Number > prototype> Method > toLocaleString() (0) | 2021.04.28 |
Array - map과 reduce (0) | 2021.02.02 |