J Scott Smith

Selecting DOM elements with Javascript

Notes - June 1st, 2015

The Selectors

Selecting elements is pretty quick and easy in Javascript even without the big bad jquery. Remember these and you’re good.

1. Select an element with an ID

// <div id="pizza"> ...

document.getElementById("pizza");

2. Select an element with a class

// <div class="pepperoni"> ...

document.getElementsByClassName("pepperoni");

3. Select an element by attribute

// <div data-dough="flour"> ...

document.getElementsByAttribute("data-dough");

4. Select an element by tag name

// <input> ...

document.getElementsByTagName("input");

5. Query selector

Selects and returns the first matching element using CSS syntax.

// <div id="crust"> ...

document.querySelector("#crust"):

6. Query selector all

Selects and returns a list of elements using CSS syntax.

//  <ul>
//      <li class="cheese"> ... 
//      <li class="sauce"> ...
//  </ul>

document.querySelectorAll("li.cheese, li.sauce");

Comments

blog comments powered by Disqus