Java Reference
In-Depth Information
Creating elements
jQuery simplifies how you create elements with JavaScript. The following code shows you one way:
var a = $("<a/>").attr({
id: "myLink",
href: " http://jquery.com",
title: "jQuery's Website"
}).text("Click here to go to jQuery's website");
$(document.body).append(a);
Let's break down this code to get a better understanding of what's taking place. First, this code calls
$() and passes it the HTML to create. In this case, it's an <a/> element:
var a = $("<a/>")
Next, it chains the attr() method to set the <a/> element's attributes:
.attr({
id: "myLink",
href: " http://jquery.com",
title: "jQuery's Website"
})
The attr() method is a lot like the css() method in that you can set an individual attribute by
passing it the attribute's name and value, or you can set multiple attributes by passing an object that
contains the attributes and their values.
The code then chains the text() method, setting the element's text:
.text("Click here to go to jQuery's website");
You can also create the same element by passing the entire HTML to $() , like this:
var a = $('<a href=" http://jquery.com" title="jQuery\'s Website">' +
"Click here to go to jQuery's website</a>");
This approach, however, can become less of a benefit and more of a hassle. Not only do you have to
keep track of which type of quote you use where, but you might also have to escape quotes.
appending elements
The append() method is similar to the DOM appendChild() method in that it appends child nodes
to the parent object. The similarities end there because jQuery's append() method is much more
flexible than its DOM counterpart. The append() method can accept a DOM object, a jQuery
object, or a string containing HTML or text content. Regardless of what you pass as the parameter
to append() , it will append the content to the DOM object.
The previous code appends the jQuery‐created <a/> element to the document's body, like this:
$(document.body).append(a);
 
Search WWH ::




Custom Search