Java Reference
In-Depth Information
Creating, Inserting, and Removing Elements
Manipulating the DOM with Prototype is a simple process. The framework extends the Element object and
allows you to create an element using a constructor, populate it with data, and remove it from the DOM.
Creating an Element
The Element object's constructor accepts two arguments: the tag name and an object containing attri-
butes and their values. The following code demonstrates creating an <a/> element and adds it to the
document's body:
var attributes = new Object();
attributes.id = “myLink”;
attributes.href = “http://www.prototypejs.org”;
attributes.target = “_blank”;
var a = new Element(“a”, attributes);
The fi rst few lines of this code create an object called attributes. You create the id, href, and target
properties and assign their values. You then create an <a/> element by using the Element object's con-
structor. You pass the string “a” as the fi rst parameter and the attributes object as the second.
Inserting an Element
The update() and insert() methods both add content to the Element object. The difference is
update() replaces all existing content while insert() simply adds the content to the existing content.
Both methods can accept a string value, containing simple text or HTML, or an Element object.
The following code creates the <a/> element from the previous code example, adds content to it, and
inserts it into the page:
var attributes = new Object();
attributes.id = “myLink”;
attributes.href = “http://www.prototypejs.org”;
attributes.target = “_blank”;
var a = new Element(“a”, attributes).update(“Go to Prototype's Website”);
$(document.body).insert(a);
This code calls the update() method, which replaces the element's existing content with the new
content as specifi ed by the data passed to it (in this example, there was no existing content). Because
the update() method returns the Element object you created, you assign the object to the variable a,
which you then pass to the insert() method of the document.body object.
Removing an Element
Removing elements from the DOM is even easier, and in fact is the same as in jQuery. You fi rst fi nd the
element you want to remove from the DOM and then call the remove() method.
$(“myLink”).remove();
Search WWH ::




Custom Search