Java Reference
In-Depth Information
This code toggles the
class‐three
CSS class. If the element already has the class, it is removed from
the element. Otherwise, it is added.
The
hasClass()
method returns
true
or
false
depending on whether or not the element has the
CSS class:
div.hasClass("class-four");
This code returns
false
because the
class‐four
CSS class isn't applied to the element.
Of course, changing an element's style isn't the only DOM‐related things MooTools can do; you can
also create, insert, and remove elements from the DOM.
Creating, inserting, and removing elements
Like Prototype, MooTools lets you create elements with the
Element
constructor:
var attributes = {
id: "myLink",
href: "mootools.net"
};
var a = new Element("a", attributes);
When you call the constructor, you pass the tag name and an object containing your
desired attributes. The preceding code creates a new
<a/>
element and populates its
id
and
href
properties. You can then set its content with the
appendText()
or
appendHTML()
methods:
a.appendText("Go to MooTools' Website");
MooTools also adds a
set()
extension method that lets you set the value of a proprietary
“property.” These are not properties in the sense of a JavaScript property using
object
.propertyName
syntax; instead, they're more of a virtual property. For example, there is an
html
property that sets the HTML of an element, and you set this property with the
set()
method,
like this:
a.set("html", "Go to MooTool's Website");
This is essentially the same as using the native
innerHTML
property, and in most cases, you'd want
to use
innerHTML
.
When you're ready to add the element to the page, use the
adopt()
method:
$(document.body).adopt(a);
This code appends the newly created
<a/>
element to the page's
<body/>
element with the
adopt()
method. Note that this doesn't replace existing content; it simply adds new content to the page. If
you need to empty an element of its children, call the
empty()
method:
$(document.body).empty();