Dojo in XPages – 9: Manipulating DOM Element Styles and Classes

We recently saw how to select DOM elements with dojo.query(). In this post, I’ll show how you can change class names and styles of the selected elements.

Dojo in XPages Series

Dojo in XPages — All Blog Posts

Adding and Removing Classes

If you have classes already set up in style sheets, you can use dojo to easily add or remove class names from one or more elements. Use this syntax if you just need to modify a single element:

dojo.addClass('ID/Node', 'myClass');
dojo.removeClass('ID/Node', 'myClass');

The first parameter can either be an element’s ID or a handle to a dojo node. (For more information about XPages element IDs, see this post.)

Chaining Dojo Methods

If you want to modify multiple elements, you can select them with dojo.query() and easily modify them with one step. You can use the single-node processing statements shown above with dojo.forEach() or you can chain the addClass() or removeClass() methods to the original query to take care of the selection and modification in a single statement.

For example, if I want to select all of the LI tags on the page and either add or remove a class from all of them, I could use one of these statements:


Changing Style Properties

Dojo has a style() method that allows you to change style properties.

To change the style of a single element, specify the element ID or a handle to a dojo node, the property name, and the value. For example, to hide a field with the ID input1, you can set it’s display property to none, as follows:'input1', 'display', 'none');

Property names are similar to CSS property names, but if the standard CSS property name has a hyphen, then the hyphen is removed and the property is written in camel case. For example, background-color changes to backgroundColor.

To change style properties on multiple elements, chain the style() method to a dojo.query(). These examples hide all odd LI elements and change the color of the event elements to red.

dojo.query('li:nth-child(odd)').style('display', 'none');
dojo.query('li:nth-child(even)').style('color', 'red');

Changing Multiple Style Properties

If you want to change multiple style properties with a single statement, you can use this syntax:


This example changes the color and font size and adds an underline. (Note that the text-decoration and font-size properties are modified to remove the hyphen and capitalize the second part.)


With these functions, you can easily modify the styling of any element on your pages.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: