JavaScript / Object / document.querySelectorAll() / 특정 CSS 선택자를 가진 모든 요소 선택하는 메서드
.querySelectorAll()
.querySelectorAll()은 특정 CSS 선택자를 가진 모든 요소를 배열로 가져오는 메서드입니다.
문법
document.querySelectorAll( 'selector' )
예를 들어
document.querySelectorAll( '.abc' )
는 클래스 값이 abc인 모든 요소를 가져옵니다.
document.querySelectorAll( '.abc, .def' );
클래스 값이 abc 또는 def인 모든 요소를 가져옵니다.
예제 1
클래스 값이 abc인 요소 중 두번째 요소의 색을 빨간색으로 만듭니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <p class="abc">Lorem Ipsum Dolor</p> <p class="abc">Lorem Ipsum Dolor</p> <p class="abc">Lorem Ipsum Dolor</p> <script> var jb = document.querySelectorAll( '.abc' ); jb[1].style.color = 'red'; </script> </body> </html>
예제 2
클래스 값이 abc인 모든 요소를 빨간색으로 만듭니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <p class="abc">Lorem Ipsum Dolor</p> <p class="abc">Lorem Ipsum Dolor</p> <p class="abc">Lorem Ipsum Dolor</p> <script> var jb = document.querySelectorAll( '.abc' ); for ( var i = 0; i < jb.length; i++ ) { jb[i].style.color = 'red'; } </script> </body> </html>
예제 3
클래스 값이 abc 또는 def인 요소의 색을 빨간색으로 만듭니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <p class="abc">Lorem Ipsum Dolor</p> <p class="abc">Lorem Ipsum Dolor</p> <p class="def">Lorem Ipsum Dolor</p> <p>Lorem Ipsum Dolor</p> <script> var jb = document.querySelectorAll( '.abc, .def' ); for ( var i = 0; i < jb.length; i++ ) { jb[i].style.color = 'red'; } </script> </body> </html>