-
querySelectorJS(javascript) 2020. 11. 23. 17:19
*혼자 내용 정리를 위해 작성하는 글이라 정확하지 않은 정보가 포함되어 있을 수 있습니다.
document.querySelector()
이번엔 document의 method 중 하나인 querySelector에 대해 다룰 예정이다.
기초적인 설명은 세 줄 뿐이다.
1. CSS selector(id, class, html tag type)를 인자(parameter)로 받아 HTMLElement를 반환하는 함수이다.
2. 인자로 받은 selector에 해당하는 HTMLElement가 document, 즉 웹페이지 내에 존재하지 않다면 null을 반환한다.
3. 만약 selector에 해당하는 HTMLElement가 여러 개일 경우 HTML에서 제일 위에 위치한 HTMLElement를 가져온다.
다음은 1, 3에 대한 예시이다.
2에 대한 예시는 따로 준비하지 않았다.
<!--예시 index.html--> <body> <h1>jo</h1> <h1>jt</h1> <script src="index.js"></script> </body>
//예시 index.js const first = document.querySelectorAll('h1'); console.log(first);
<!--출력 결과--> <h1>jo</h1>
1:
우선 HTMLElement라는 용어가 좀 생소하다.
적어도 나는 그랬다.
하지만 '출력 결과'를 보면 대략 감이 온다.
<h1>jo</h1>
한 줄 전부가 HTMLElement인 것이다.
3:
index.html에 h1에 해당하는 tag는 두 개이다.
하지만 제일 위의 HTMLElement만 출력되는 것을 확인 할 수 있다.
주의할 점:
querySelector 함수의 인자는 CSS selector 문법에 맞게 입력해야한다.
id이면 #, class이면 . (dot)
특정 HTML tag이면 해당 tag의 type
이에 위반하면 SYNTAX_ERR가 발생하므로 주의하자.
혹은 console에서 SYNTAX_ERR가 보인다면 querySelector에서 인자값을 제대로 입력했는지 확인해보자.
이 정도만 알면 querySelector()를 사용할 때 큰 무리가 없을 것 같다.
하지만 정교한 selector 지정이 가능한 'A more complex selector', 'Negation' 두 부분까지 더 언급하려 한다.
예시를 위해 아래의 코드를 준비했다.
// 예시 index.js const first = document.querySelector("div.user.main input[name='login']"); const second = document.querySelector("div.user:not(.main) input[name='login']"); function init() { console.log(first.value); console.log(second.value); } init();
<!-- 예시 index.html --> <body> <div class="user main"> <input name="login"/ value = "1"> </div> <div class="user"> <input name="login"/ value = "2"> </div> <script src="index.js"></script> </body>
// 출력 결과 1 2
우선 index.js에 두 개의 querySelector를 보자.
안의 parameter가 엄청 복잡하다.
복잡한만큼 selector를 타겟팅할 때 명확할 것이다.
첫 번째 selector를 해석해보자.
살펴보면 div로 시작하는 코드 부분과 input으로 시작하는 코드 사이에 공백이 있다.
공백을 기준으로 뒤쪽 selector가 최종 선택되는 HTMLElement가 된다는 뜻이다.
그럼 공백 앞쪽 selector는 무엇일까?
지정하려는 HTMLElement를 감싸는 HTMLElement에 대한 selector이다.
그럼 div의 selector부터 분석해보자.
div tag일 것 + class로 user를 가질 것 + class로 main을 가질 것
이어서 input의 selector를 분석해보자
input tag일 것 + name 속성 값이 'login'일 것
이 두 조건을 합치면 index.html의 어떤 input을 지정하려는지 알 수 있다.
이번에는 두 번째 selector를 해석해보자.
첫 번째 selector와 다른 것은 ':not(.main)' 부분이다.
매우 직관적인 해석이 가능하다.
그럼 div의 selector를 분석해보자.
div tag일 것 + class로 user를 가질 것 + class로 main을 가지지 않을 것
마찬가지로 index.html의 어떤 Input을 지정하려는지 알 수 있다.
참고 사이트:
developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
'JS(javascript)' 카테고리의 다른 글
localStorage, JSON, stringfy, parse (0) 2020.11.24 setInterval (0) 2020.11.24 var, let (0) 2020.11.24 Date, innerHTML (0) 2020.11.23 document interface (0) 2020.11.23