Programming node.js, php, python, java…

Menu

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.

document.getElementsByName('content')

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

// Get by ID
document.getElementById('wp_fs_link')</code>
// By class names
document.getElementsByClassName('mceButton')

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.

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.

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.