.attr()

Description

.attr() acts as getters and setter.

If .attr() is passed two values, one for the attribute name and one for the attribute value, then it sets an attribute, but if it's invoked with one argument, it gets a value.

Syntax for getter

.attr(attributeName) gets the value of an attribute for the first element in the set of matched elements. attributeName is the name of the attribute to get.

The return value is a string containing the attribute value.

Syntax for setter

  • .attr(attributeName, value)
    Set one or more attributes for the set of matched elements. attributeName: The name of the attribute to set. value: A value to set for the attribute
  • .attr(map)
    map: A map of attribute-value pairs to set
  • .attr(attributeName, function)
    attributeName: The name of the attribute to set. function: A function returning the value to set

Return value is the jQuery object, for chaining purposes.

The following code sets several attributes at once.


$('#my').attr({/*  w  w w .j a  v a  2s .c  om*/
 alt: 'alt value',
 title: 'title value'

});

The following uses the computed attribute values.


$('#my').attr('title', function() {
    return this.alt + ' - added'

});

Set image src

The following code sets src attribute from title attribute on the image.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- w w w  . ja va2s . c  o  m-->
                $("img").attr("src", function() {
                  return "/images/" + this.title;
                });

        });
    </script>
  </head>
  <body>
    <body>
      <img title="a.gif"/>
    </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

attr and loop

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as jQuery's .each() method.

The following example illustrates both cases:


<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
        .blue {<!--from  ww w  .j  ava 2  s  .  c o m-->
          background-color: blue;
        }
        </style>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js">
        </script>
        <script>

            $(function(){
                $("p#myID").attr("class","blue");
                var attribute = $("p#myID").attr();
                document.writeln(attribute);
            });
        </script>
    </head>
    <body>
        <p id="myID">
            This is a test.
        </p>
    </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

.attr getter demo

Get attribute from tag


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  w  w  w .  j av a2s .  com-->
            var title = $("em").attr("title");
            $("div").text(title);
        });
    </script>
  </head>
  <body>
    <em title="title value">em</em>
    <div></div>
  </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

.attr setter demo

Use attr() to set the attribute value.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){<!--from  w  w w .  j a v  a  2s .c  o  m-->
          $("div[id]").one("click", function(){
              var idString = $(this).text() + " = " + $(this).attr("id");
              $(this).text(idString);
          });

    });
    </script>
  </head>
  <body>
      Click to see.
      <div>div</div>
      <div id="hey">div</div>
  </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

access a property on the first matched element

attr(name): access a property on the first matched element.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  w  w w  .j  a v a  2  s  .  co  m-->
            var title = $("em").attr("title");
            $("div").text(title);
        });
    </script>
  </head>
  <body>
    <body>

      <em title="title value">
      <div></div>
    </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

Add attribute and clear attribute


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type='text/javascript'>
        $(document).ready(<!--  w  ww .  ja v  a2s  .com-->
          function() {
            $('div').hover(
              function() {
                $(this).attr('id', 'justAdd');
                $(this).text('This element\'s ID is: ' + $(this).attr('id'));
              },
              function() {
                $(this).attr('id', '');
                $(this).text('This element\'s ID has been removed.');
              }
            );
          }
        );

        $('a').removeAttr('title');
    </script>
    <style type='text/css'>
div {
    width: 350px;
    padding: 10px;
    border: 1px solid rgb(200, 200, 200);
    background: #93cdf9;
    margin: 5px;
}
div#justAdd {
    background: #6faddd;
}
    </style>
  </head>
  <body>
     <div>Mouse over to change this element's id.</div>
  </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

Set Image URL title alt


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--   w ww .  jav  a 2  s  .com-->
             $("img").attr({
                 src: "http://java2s.com/style/logo.png",
                 title: "java2s.com",
                 alt: "Logo"
             });
             $("div").text($("img").attr("alt"));
        });
    </script>
  </head>
  <body>
    <body>
      <img />
      <div></div>
  </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

attr value calculation

attr(key, fn) with function


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--   w w  w  .  j a va  2s. c  o  m-->
             $("div").attr("id", function (arr) {
                  return "div-id" + arr;
                 })
                .each(function () {
                  $("span", this).html("(ID = '<b>" + this.id + "</b>')");
             });
        });
    </script>
  </head>
  <body>
    <body>
      <div>A<span></span></div>
      <div>B<span></span></div>
      <div>C<span></span></div>
    </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()

.attr with function return value

Set attribute with the returned function value


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type='text/javascript'>
$(document).ready(<!--from w w w . j  av a  2  s. c  o  m-->
  function() {
    $('li').attr(
      'id',
      function() {
        return 'tmp' + $(this).text();
      }
    );
  }
);
    </script>
    <style type='text/css'>

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
ul li {
    margin: 3px;
    padding: 3px;
}
li#tmpA {
    background: #d7b05b;
}
li#tmpB {
    background: #d3988a;
}
li#tmpC {
    background: #8ad3a6;
}
li#tmpD {
    background: #8aa9d3;
}
    </style>
  </head>
  <body>
     <ul>
        <li>A</li>
        <li>B</li>
        <li>C</li>
        <li>D</li>
     </ul>
  </body>
</html>

Click to view the demo

The code above generates the following result.

.attr()
Home »
  Javascript Tutorial »
    jQuery Reference »
      DOM
...
$("html tags")
.add()
.addClass()
.after()
.andSelf()
.append()
.appendTo()
.attr()
.before()
.children()
.clone()
.closest()
.contents()
.css()
.detach()
.filter()
.first()
.get()
.has()
.hasClass()
.height()
.html()
.index()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.is()
.last()
.map()
.next()
.nextAll()
.nextUntil()
.not()
.offset()
.offsetParent()
.outerHeight()
.outerWidth()
...