Java Reference
In-Depth Information
Let's break the document_ready() function down to get a better understanding of what's taking place.
First, you create the <a/> element with the document.createElement() method.
var a = $(document.createElement(“a”));
Instead of simply assigning the element to a variable, you pass it to the jQuery function so you can use
the jQuery methods to populate it with attributes and text. Next, you pass the document.body object
to the jQuery function and call the append() method.
$(document.body).append
(
Appending Elements
The append() method is similar to the DOM appendChild() method in that it appends child nodes
to the DOM object. The append() method accepts a DOM object, a jQuery object, or a string containing
HTML content. Regardless of what you pass as the parameter to append(), it will append the content
to the DOM object. In the case of this code, you pass the jQuery object that references the <a/> element
you created earlier, and you assign attributes to the element.
a.attr(“id”, “myLink”)
.attr(“href”, “http://jquery.com”)
.attr(“title”, “jQuery's Website”)
After you assign the id, href, and title attributes, you then add text to the link, and there are a couple
of ways you can do this. You could use the append() method and pass the text to it, or you could use the
text() method. Either method would result in the same outcome, but use text() in this case simply
because you haven't used it yet.
.text(“Click here to go to jQuery's website.”)
);
Remember what makes method chaining possible in jQuery is that most methods return the jQuery
object you called the method on. So the text() method returns the jQuery object referencing the <a/>
element object to the append() method called on the jQuery object referencing the document.body
object.
You could rewrite this code in a couple of other ways. First, you could do this:
function document_ready()
{
var a = $(document.createElement(“a”))
.attr(“id”, “myLink”)
.attr(“href”, “http://jquery.com”)
.attr(“title”, “jQuery's Website”)
.text(“Click here to go to jQuery's website.”);
$(document.body).append(a);
}
Search WWH ::




Custom Search