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.
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:
dojo.query('li').addClass('myClass'); dojo.query('li').removeClass('myClass');
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:
dojo.style('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:
dojo.query('x').style({ property:value, property:value, property:value })
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.)
dojo.query('li').style({ color:"#00FF00", textDecoration:"underline", fontSize:"24px" })
With these functions, you can easily modify the styling of any element on your pages.
