A good[ish] website

Web development blog, loads of UI and JavaScript topics

Getting DOM elements with JavaScript

Filed under: JavaScript— Tagged with: DOM

️️2015.03.19 I just noticed that any attribute can be queried with querySelectorAll, added that to the article. 2015.04.19 Added a section with querySelector and querySelectorAll.

Get element by id

var el = document.getElementById('my-element')

MDN article.

Get element by tag name

This gets all the divs.

var el = document.getElementsByTagName('div')

MDN article.

Get element by class name

The following doesn't work in IE8, but is otherwise an splendid method.

var el = document.getElementsByClassName('my-element')

MDN article.

The following works down to IE8.

var el = document.querySelectorAll('.my-element')

MDN article.

Get element by name

Element that has a name attribute.

<div name="hello"></div>

Can be queried like this:

var xyz = document.getElementsByName('xyz')

Get pretty much anything

I think .querySelector() and .querySelectorAll() are underrated compared how handy they are. Any element can be queried using them.

// Returns a nodelist with all the elements with a class .module
var els = document.querySelectorAll('.module')

// Returns the first element with a class .module
var els = document.querySelector('.module')

// Returns divs with .note and .alert classes
var els = document.querySelectorAll('div.note, div.alert')

// Returns all span elements within #thing
var els = document.querySelectorAll('#thing > span')

In fact, any CSS type of selector query can be used.

The string argument pass to querySelector must follow the CSS syntax.

And both of them work down to IE8 :)

MDN article for querySelectorAll.

MDN article for querySelector

Get a descendant element

Just as an example, imagine a table of contents plugin that needs to be enabled if there are any h tags in the #content section:

// Grab #content and h2 elements in it
var foo = document.getElementById('content').getElementsByTagName('h2')
if (foo.length > 0) {
  // Kick off the table of contents plugin here, for example

Or even more simply with querySelectorAll:

var el = document.querySelectorAll('#content > h2')
if (el) {
  // Kick off the ToC plugin here

Get elements by an arbitrary attribute

I thought this was impossible, but the querySelectorAll shows it's power again. The following gets elements that have data-src attribute:

var lazyImgs = document.querySelectorAll('img[data-src]')

MDN article.


Native JavaScript is much faster than library methods, SitePoint has a good article, with benchmark results.

Also, you might want to see these jsperf test here and here, getting elements by ID is the fastest.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!