querySelector method

Retrieves the first Document Object Model (DOM) element node from descendants of the starting element node that match any selector within the supplied selector string.

Internet Explorer 8



HRESULT retVal = object.querySelector(v, pel);


v [in]

Type: BSTR

The selector string.

pel [out, retval]

Type: IHTMLElement

A DOM element node, or NULL if the search cannot find an element that matches the selector string.

Return value


If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

Standards information


The document search order is depth-first. This method returns the first element found. To find all matching nodes, use IElementSelector::querySelectorAll.

The scope of the returned element node is limited to the descendants of the starting element node. If the starting element is document, the search returns nodes from the entire document.

This method does not return the starting element node. For example, div.querySelector("p div") will never return the DIV element that it starts with.

The pseudo-class selectors :hover, :focus, and :active are supported. Selectors that contain :visited or :link are ignored and no elements are returned.

You can search namespaced elements using a selector syntax based on prefix instead of the namespaceURI, for example "nsPrefix \: element", where "nsPrefix" is the prefix of a given element.

Selectors are described in detail in Understanding CSS Selectors and W3C Selectors.


This example illustrates using the IElementSelector::querySelector method to return a list item based on a selector string. The example shows a div element that contains a list whose items are each defined with a different selector string. The example includes three buttons that use the IElementSelector::querySelector method to return the appropriate item from the list.

Code example: http://samples.msdn.microsoft.com/workshop/samples/css/SelectorsAPI/querySelector.html

<div id="mystery">
   <span>Mystery Items</span>
      <li class="animal">cat</li>
      <li class="vegetable">broccoli</li>
      <li class="mineral">silver</li>

<input onclick="getAnimal()" type="button" value="Animal">
<input onclick="getVegetable()" type="button" value="Vegetable">
<input onclick="getMineral()" type="button" value="Mineral">

<div id="inOut"></div> 

Each button calls a JavaScript function that uses the IElementSelector::querySelector method to return a list item based on its selector string.

function getAnimal() {
function getVegetable() {
   inOut.innerHTML = document.getElementById('mystery').querySelector('li.vegetable').innerHTML;
function getMineral() {
   inOut.innerHTML = document.getElementById('mystery').querySelector('li.mineral').innerHTML;

See also

Other Resources
W3C Selectors API
W3C Selectors