jQuery Methods: attr()

By: Dusty Arlia
Published on Friday, April 4, 2014, 02:10 PM
Last Updated on Saturday, July 11, 2015 at 9:03 PM
Total Updates: 2

The jQuery attr() method is used to get and set the value of HTML attributes. Here are some example of its syntax:

$("a").attr("href");   //get the href attribute of the first link
$("a").attr("target", "_blank");   //set the target attribute to "_blank" for all links in the jQuery object
$("a").attr("target", function() {
	if (this.host == location.host) {
		return "_self"
	} else {
		return "_blank"
$("a").attr({target: function() {...}});
$("#first_link").attr("href","http://www.whiterootmedia.com");   //set the href attribute of the #first_link
$("#logo").attr({src:"logo.png",   //set 4 attributes at once
				 alt:"WRM Tree",