W3Schools.com

jQuery HTML attr() Method

jQuery HTML Methods jQuery HTML Methods

Example

Set the width attribute of an image:

$("button").click(function(){
  $("img").attr("width","150");
});

Try it yourself »

Definition and Usage

The attr() method sets or returns attribute values of selected elements.

This method works differently depending on the parameters.


Return Attribute Value

Return the value of an attribute for the selected element.

Syntax

$(selector).attr(attribute)

Try it yourself »

Parameter Description
attribute Specifies the attribute to get the value of


Set Attribute/Value

Set the attribute and value of the selected elements.

Syntax

$(selector).attr(attribute,value)

Try it yourself »

Parameter Description
attribute Specifies the name of the attribute
value Specifies the value of the attribute


Set Attribute/Value Using a Function

Using a function to set the attribute value for the selected elements.

Syntax

$(selector).attr(attribute,function(index,oldvalue))

Try it yourself »

Parameter Description
attribute Specifies the name of the attribute
function(index,oldvalue) Specifies a function that returns the attribute value to set.
  • index - Optional. Receives the index position of the selector
  • oldvalue - Optional. Receives the current attribute value of the selector


Set Multiple Attribute/Value Pairs

Set one or more attributes and values for the selected elements.

Syntax

$(selector).attr({attribute:value, attribute:value, ...})

Try it yourself »

Parameter Description
{attribute:value, attribute:value, ...} Specifies one or more attribute/value pairs


jQuery HTML Methods jQuery HTML Methods


WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE