Some of the Javascript DOM methods

Even if the JQuery or any other Javascript library dominates the DOM manipulation, there is old Javascript DOM API which is used by the libraries.

For debug or to test out the methods use the, browser consoles where you can execute the code.

Selecting elements, selector methods. DOM methods can be accessed under the document object.

First method allows to select all the elements by tag name, I have not seen many cases where it’s used.

document.getElementsByTagName('tag name')

Second selecting by name, is very useful when you have to do validation for forms.


There is list of other selectors which can be used to select by Id and class name.

// Get by ID

// By class names

Another set of methods are querySelector finds only one element and querySelectorAll find all the matching elements. Only problem is the compatibility with older browsers of IE(5,6,7), FF(2.0,3.0) and some Opera versions, you can look the overall table .
These methods are special because you can use the CSS selectors. Most of the JQuery element selections are based on querySelector.

document.querySelector('a + img')</code>

document.querySelectorAll('ul &gt; li')


More and more the web sites get dynamic(AJAX) and you need to create the DOM on the fly. Also the code blocks are heavier and contains more then just one element. So it is cleaner to use some html template library like JQuery templates, Mustache, Handlebars and others. But for one element DOM appending use the createElement method.

var p = document.createElement('p');
p.innerHTML = 'This is <em>the</em> content';</code>

// Add the element into heading elemnt

Each call to methods innerHTML, appendChild or any methods which changes DOM structures are slow when you are making the massive changes, so be aware of that!

Same example in JQuery

// JQuery
$('h2:first').append($('<p>', { text: 'This is the content' }));

As an last example we create typical form and change the border color to red if the text box is empty, demo is.

Well I can not put HTML code because it is not escaped, but the Javascript one is here:

var form = document.forms['check-username']
, username = form['username']
, button = form['check'];</code>

button.onclick = function(e) {
var len = username.value.length; = (len &lt;= 0) ? 'solid 2px red' : '';

As you can see lot of the Javascript’s official DOM methods are really long to type, so make sure your IDE/text editor has good auto complete feature. Besides the verbose of method names it is good to use these methods when you need performance without the bells and whistles which comes with libraries.