Web Development with jQuery®

(Elliott) #1

(^96) ❘ CHAPTER 4 MANIPULATING CONTENT AND ATTRIBUTES


FIGURE 4-4


Setting Multiple Attributes


Setting multiple attributes is done by providing a JavaScript Object Literal to the attr() method,
which is demonstrated in the following example:

var input = $('<input/>').attr({
type : 'radio',
name : 'documentAttributeMarx',
id : 'documentAttributeGrouchoMarx',
value : 'Groucho'
});

The preceding example creates a new element using jQuery identical to this one in HTML:


<input type='radio'
name='documentAttributeMarx'
id='documentAttributeGrouchoMarx'
value='Groucho' />

Passing a string such as '<input/>' tells jQuery to create a new element by parsing the snippet
of HTML you’ve passed to it. In this example, you create a single new element, which can then
be manipulated using jQuery’s various API methods: You call the attr() method and pass an
object containing the type, name, id, and value attributes and their corresponding values.

The resulting element assigned to the variable named input can then be further operated on with
other API methods or inserted into the document using the various methods you learn about later in
this chapter, such as html(), prepend(), append(), and so on.

http://www.it-ebooks.info

Free download pdf