Java Reference
In-Depth Information
Manipulating Style
Prototype provides you several methods to change an element's style, and they are not unlike those
found in the jQuery framework.
The setStyle() method lets you set individual style properties. To set style in this way, you must create
an object, and create properties for this object whose names are those of CSS properties. For example, the
following code sets an element's text color to red and underlines it:
var styles = new Object();
styles.color = “red”;
styles.textDecoration = “underline”;
$(“myDiv”).setStyle(styles);
As previously mentioned in the jQuery section, changing an element's style in this manner is
undesirable because style should be defi ned in the page's style sheet. A better alternative is to manipu-
late an element's CSS class, and Prototype allows you to easily do that with the addClassName(),
removeClassName(), toggleClassName(), and hasClassName() methods.
The fi rst method, addClassName(), adds a CSS class name to the element. Simply pass the class name
to the method, and it is applied to the element.
$(“myDiv”).addClassName(“someClass”);
The second method, removeClassName(), removes the specifi ed class from the element. The following
code adds a class name and then removes it:
$(“myDiv”).addClassName(“someClass”)
.removeClassName(“someClass”);
This code isn't very practical, but it demonstrates how both methods are used. Next is the
toggleClassName() method. This method checks if the specifi ed class is applied to the element
and removes it if so. If the class name isn't found, then it applies the class to the element.
$(“myDiv”).hasClassName(“someClass”);
$(“myDiv”).toggleClassName(“someClass”);
$(“myDiv”).hasClassName(“someClass”);
This code demonstrates the toggleClassName() method and the fourth method: hasClassName().
The fi rst line of code checks if the someClass CSS class is applied to the element. Since it's not, this method
returns false. The second line calls the toggleClassName() method, which adds the someClass
CSS class to the element. The fi nal line calls hasClassName() again, which now returns true since
someClass was added in the previous line.
These CSS methods closely resemble those of jQuery. However, other types of DOM manipulation such
as creating and inserting elements are areas where Prototype differs greatly from jQuery. However, as
you'll soon see, removing DOM objects is very similar.
Search WWH ::




Custom Search