Select DOM elements

Selecting one or more DOM elements is one of the basic features of jQuery. The equivalents to $() in JavaScript are document.querySelector() or document.querySelectorAll() functions.

Refer to the following code snippet to learn how to select DOM elements in both jQuery and vanilla JavaScript:

// Select multiple elements by "class" using jQuery.
$(".blog-post");
// Select the first instance of an element by "class" using vanilla JavaScript.
document.querySelector(".blog-post");

// Select multiple elements by "class" using vanilla JavaScript.
document.querySelectorAll(".blog-post");

Additional methods:

  1. getElementsByClassName()
    let elements = element.getElementsByClassName('blog-post'); // no "." used here to access the class
    
  2. getElementsById()

    let elements = element.getElementsById('post-wrapper'); // no "#" used here to access the id
    
  3. getElementsByTagName()

    let elements = element.getElementsByTagName('img')