A good[ish] website
Web development blog, loads of UI and JavaScript topics
️️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 withquerySelector
andquerySelectorAll
.
var el = document.getElementById('my-element')
This gets all the divs.
var el = document.getElementsByTagName('div')
The following doesn't work in IE8, but is otherwise an splendid method.
var el = document.getElementsByClassName('my-element')
The following works down to IE8.
var el = document.querySelectorAll('.my-element')
Element that has a name attribute.
<div name="hello"></div>
Can be queried like this:
var xyz = document.getElementsByName('xyz')
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
.
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
}
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]')
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.