Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Element Getters and Setters > Getting and Setting HTML Attributes

Getting and Setting HTML Attributes

The attr() method is the jQuery getter/setter for HTML attributes, and it adheres to each of the generalizations described above. attr() handles browser incompatibilities and special cases, and allows you to use either HTML attribute names or their JavaScript property equivalents (where they differ). For example, you can use either “for” or “htmlFor”, and either “class” or “className”. removeAttr() is a related function that completely removes an attribute from all selected elements. Here are some examples:

// Query the action attr of 1st form
$("form").attr("action");
// Set the src attribute of element with id icon
$("#icon").attr("src", "icon.gif");
// Set 4 attributes at once
$("#banner").attr({src:"banner.gif",
                   alt:"Advertisement",
                   width:720, height:64});
// Make all links load in new windows
$("a").attr("target", "_blank"); 
// Compute the target attribute to load local links
// locally and load off-site links in a new window
$("a").attr("target", function() {
    if (this.host == location.host) return "_self"
    else return "_blank";                
});
// We can also pass functions like this
$("a").attr({target: function() {...}}); 
// Make all links load in this window
$("a").removeAttr("target"....

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint