Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Document.querySelector()

번역 작업 진행중입니다.

selector들이 지정한 그룹과 일치하는 document 내의 첫 번째 element를 반환합니다. (depth-first를 우선적으로 사용해 문서의 노드들을 탐색합니다. 자식 노드의 양에 따라 첫 element를 검색하는 것을 순차적으로 반복하여 탐색합니다. )

Syntax

element = document.querySelector(selectors);

where

  • element는 element object 입니다.
  • selector는 쉼표로 구분되는, 하나 이상의 CSS selectors를 포함하는 문자열입니다.

Example

이 예제에서는 "myclass" 라는 클래스를 사용하는 문서의 첫 번째 element를 반환합니다.

var el = document.querySelector(".myclass");

Example: Powerful


다음 예제와 같이 selector는 정말 강력할 수 있습니다. <div class="user-panel main"> 내에서 <input name="login"/> 를 사용하는 첫 element를 반환합니다.

var el = document.querySelector("div.user-panel.main input[name=login]");

Notes

일치하는 것을 찾지 못하면 null을 반환합니다. 그렇지 않으면 일치하는 것 중 가장 앞서 쓰인 element 를 반환합니다.

만약 selector가 일치하는 ID(<div id="">)를 찾았으나, 잘못 사용하여 문서내에 일치하는 ID가 여러개일 경우 가장 앞서 쓰인 element를 반환합니다.

selector에서 지정한 그룹이 유효하지 않을 경우 SYNTAX_ERR 예외를 throw합니다.

querySelector() 는 Selectors API에서 소개되었습니다.

querySelector의 문자열 인자는 반드시 CSS 구문(CSS selector)을 따라야 합니다.

CSS Pseudo-elements(가상 요소)는 Selectors API 에 명시된 대로 어떠한 element도 결코 반환하지 않습니다.

예를들어 ":"(colon) 또는" "(space) 를 사용했을 때 CSS 구문을 따르지 않는 selector 또는 ID를 일치시키려면, 반드시 \(backslash)와 같은 escape 문자를 필요로 합니다. \는 JavaScript의 escape 문자이기 때문에, 당신이 literal string을 입력하려고 한다면 반드시 두번 escape 해야 합니다. (한번은 Javascript string 에 사용하고, 또 다른 한 번은 querySelector에 사용됩니다.)

<div id="foo\bar"></div>
<div id="foo:bar"></div>

<script>
  console.log('#foo\bar')               // "#fooar"
  document.querySelector('#foo\bar')    // Does not match anything

  console.log('#foo\\bar')              // "#foo\bar"
  console.log('#foo\\\\bar')            // "#foo\\bar"
  document.querySelector('#foo\\\\bar') // Match the first div

  document.querySelector('#foo:bar')    // Does not match anything
  document.querySelector('#foo\\:bar')  // Match the second div
</script>

Specifications

Specification Status Comment
Selectors API Level 2
The definition of 'document.querySelector()' in that specification.
Working Draft  
Selectors API Level 1
The definition of 'document.querySelector()' in that specification.
Recommendation Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1 3.5 8 10 3.2
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 2.1 (Yes) 9 10.0 3.2

See also

문서 태그 및 공헌자

 이 페이지의 공헌자: DeadIntegral, imskojs
 최종 변경: DeadIntegral,