jQuery attr()

jQuery attr() method is the used to get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

Below the syntax of attr().

Return the value of an attribute:


Set the attribute and value:

$(selector).attr(attribute, value);

Set attribute and value using a function:


Set multiple attributes and values:

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

Parameter Description
attribute Specifies the name of the attribute
value Specifies the value of the attribute
function(index,currentvalue) Specifies a function that returns the attribute value to set.
  • index - Receives the index position of the element in the set
  • currentvalue - Receives the current attribute value of selected elements

# Example1 - Set the value of input field

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>jQuery attr()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(document).ready(function() {
  $("#button").click(function() {
     $("#logoimg").attr("width", 175);
 <p><img src='https://nexladder.com/images/nexlogo.png' alt='' id="logoimg" /></p>
 <button style="margin:0 0 10px 0;background:#e8e8e8;" class="btn" id="button">Click here to set the width attribute of the image</button><br />