.attr()

.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)
Get the value of an attribute for the first element in the set of matched elements. attributeName: The name of the attribute to get

Return value

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

The jQuery object, for chaining purposes.

Setting several attributes at once


$('#my').attr({
 alt: 'alt value',
 title: 'title value'

});

Computed attribute values


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

});

Sets src attribute from title attribute on the image.

 
<html>
  <head>
    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
                $("img").attr("src", function() {
                  return "/images/" + this.title;
                });

        });
    </script>
  </head>
  <body>
    <body>
      <img title="a.gif"/>
    </body>
</html>
  
Click to view the demo

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 {
        Background-color: blue;
        }
        </style>
        <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/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

Get attribute from tag

 
<html>
  <head>
    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            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

Use attr() to set the attribute value.

 
<html>
  <head>

    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
          $("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

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

 
<html>
  <head>
    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            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

Add attribute and clear attribute

 
<html>
  <head>
    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type='text/javascript'>
        $(document).ready(
          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

Set Image URL title alt

 
<html>
  <head>
    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("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

attr(key, fn) with function

 
<html>
  <head>
    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("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

Set attribute with the returned function value

 
<html>
  <head>
    <script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
    <script type='text/javascript'>
$(document).ready(
  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
Home 
  JavaScript Book 
    jQuery  

DOM:
  1. jQuery DOM
  2. $("html tags"):generate code with the jQuery wrapper function.
  3. .add()
  4. .addClass()
  5. .after()
  6. .andSelf()
  7. .append()
  8. .appendTo()
  9. .attr()
  10. .before()
  11. .children()
  12. .clone()
  13. .closest()
  14. .contents()
  15. .css()
  16. .detach()
  17. .filter()
  18. .first()
  19. .get()
  20. .has()
  21. .hasClass()
  22. .height()
  23. .html()
  24. .index()
  25. .innerHeight()
  26. .innerWidth()
  27. .insertAfter()
  28. .insertBefore()
  29. .is()
  30. .last()
  31. .map()
  32. .next()
  33. .nextAll()
  34. .nextUntil()
  35. .not()
  36. .offset()
  37. .offsetParent()
  38. .outerHeight()
  39. .outerWidth()
  40. .parent()
  41. .parents()
  42. .parentsUntil()
  43. .position()
  44. .prepend()
  45. .prependTo()
  46. .prev()
  47. .prevAll()
  48. .prevUntil()
  49. .remove()
  50. .removeClass()
  51. .removeAttr()
  52. .replaceAll()
  53. .replaceWith()
  54. .siblings()
  55. .scrollLeft()
  56. .scrollTop()
  57. .slice()
  58. .text()
  59. .toArray()
  60. .toggleClass()
  61. .unwrap()
  62. .val()
  63. .wrap()
  64. .wrapAll()
  65. .wrapInner()
  66. .width()