Selectors API: querySelector and querySelectorAll

Use querySelector and querySelectorAll to access DOM elements. They accept any CSS selector, so you are no longer restricted by the selection of elementsid

Introduction

jQuery etc.DOMIn the past, libraries and the other features they provided have greatly increased their popularity, thanks to an easy way to select page elements.

Traditionally, browsers only provide a way to select DOM elements-through itsidAttributes withgetElementById(),bydocumentpurpose.

Selector API

Since 2013Selector API, DOM allows you to use two more useful methods:

  • document.querySelector()
  • document.querySelectorAll()

They can be used safely,As caniuse.com tells us, And apart from all other modern browsers, they are fully supported even on IE9, so there is no reason to avoid using them unless you need to support IE8 (with partial support) and below.

They accept any CSS selector, so you are no longer restricted by the selection of elementsid.

  • document.querySelector()Return a single element, the first one found
  • document.querySelectorAll()Return all the elements wrapped in the NodeList object.

These are all valid selectors:

  • document.querySelector('#test')
  • document.querySelector('.my-class')
  • document.querySelector('#test .my-class')
  • document.querySelector('a:hover')

Basic example from jQuery to DOM API

The following is a translation of converting the popular jQuery API into a native DOM API call.

Selection basisid

$('#test')
document.querySelector('#test')

we usequerySelectorsinceidUnique in the page

Selection basisclass

$('.test')
document.querySelectorAll('.test')

Select by label name

$('div')
document.querySelectorAll('div')

A more advanced example of jQuery to DOM API

Select multiple items

$('div, span')
document.querySelectorAll('div, span')

Select by HTML attribute value

$('[data-example="test"]')
document.querySelectorAll('[data-example="test"]')

Selection via CSS pseudo-classes

$(':nth-child(4n)')
document.querySelectorAll(':nth-child(4n)')

Select the descendants of the element

Such as allliElements under#test:

$('#test li')
document.querySelectorAll('#test li')

Download mine for freeJavaScript beginner's manual


More browser tutorials: