From the course: Learning App Building with Vanilla JavaScript

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Element selection with vanilla JavaScript

Element selection with vanilla JavaScript - JavaScript Tutorial

From the course: Learning App Building with Vanilla JavaScript

Start my 1-month free trial

Element selection with vanilla JavaScript

- Vanilla JavaScript supports numerous different ways of selecting elements, both single and collections, including references their IDs, classes, and tag names. However, the easiest way to select elements with vanilla JavaScript is to specify CSS selectors, just as you would with jQuery, for instance. Vanilla JavaScript includes two methods that accept CSS selectors to select elements. The querySelector method returns a single element. If you know you're targeting a single element, say, with an ID value, which can occur only once in a web page, then querySelector is a great choice. Now, you can also use querySelector even when you're passing a selector that may match multiple elements. By design, querySelector will return only the first element that matches. So this can be a useful shortcut if you're sure that the first match is the element you want. If you instead want to select a collection of elements, then querySelectorAll is a better choice. This method returns multiple elements…

Contents