Wednesday, October 9, 2013

Dojo: Using dojo.query with pseudo-selectors

Changing HTML markup programmatically is dependent on locating nodes. You may go the traditional way of  selecting HTML elements in Javascript by using the browser's native DOM API like "document.getElementsByTagName( )" and "document.getElementsByClassName( )". But your code can get long, verbose and slow.

dojo.query is a better, faster, and more compact way to do this. It can also handle sophisticated DOM element relationships.

dojo.query() returns a list of DOM nodes based on a CSS selector.

Using dojo.query with pseudo-selectors is very interesting because it's a very compact way of getting a list of DOM nodes with several attributes.

Example:
Get the input checkbox elements with its "checked" property equal to true (a checked checkbox element) contained within an unordered list with an ID of  "sidebarCategories", then put the focus on the first checked input checkbox.

var checkboxes = dojo.query("ul#sidebarCategories  input[type=checkbox]:checked");
if (checkboxes.length > 0) {
    checkboxes[0].focus();
} 

Now that code is pretty compact and clean.

Check out the dojo.query documentation for more simple and compound queries using CSS, descendant and attribute selectors.

No comments:

Post a Comment