This is a little primer on selecting elements from your HTML without using a library like jQuery. I know jQuery really makes it easy to select elements, but with browsers becoming more standards compliant these tasks could be done without using it.

Say you want to select an element by its ID attribute.  You could do something like this:

//Legacy Browser
var container = document.getElementById('id');
//Modern Browser
var container = document.querySelector('#id');    

Or you might want to select all elements within another element with an ID.  You could try something like this:

//Legacy Browser
var list = document.getElementById('id').getElementsByTagName('li');
//Modern Browser
var list = document.querySelectorAll('#id li');

Maybe you need to grab all elements with a certain class name..

var elements = document.getElementsByClassName('classname');

Here is one for selecting all elements with a certain tag name…

var elementsByTag = document.getElementByTagName('span');

This one will select an element with an specified ID and a sub-element with a certain tag name:

var subElements = document.getElementId('id').getElementByTagName('span');

Here are a few snippets to get the HTML, head, or body elements:

//Get html tag
var htmldoc = document.documentElement;
//Get head tag
var headelements = document.head;
//Get body tag
var bodyelements = document.body;

This one will get all “p” tags in the document:

var allparagraphTags = document.getElementsByTagName('p');

These selectors should work in most browsers, including IE8 or greater:

//Element with foo as ID
//Elements with bar as class
//All span elements with bar as class, and an element with an ID of foo
document.querySelectorAll('.bar span, #foo');
//Anchor elements with danger in the href attribute


Most Visited