.attr()

In this chapter you will learn:

  1. Description for .attr()
  2. Syntax for .attr() getter
  3. Syntax for .attr() setter
  4. How to set image src from its title
  5. attr and loop
  6. .attr getter demo
  7. .attr setter demo
  8. access a property on the first matched element
  9. Add attribute and clear attribute
  10. Set Image URL title alt
  11. attr value calculation
  12. .attr with function return value

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({
 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><!-- j  a v a  2s  .c  om-->
  <head>
    <script src="http://java2s.com/style/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

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><!-- ja v a 2 s . com-->
<html>
    <head>
        <style type="text/css">
        .blue {
          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

.attr getter demo

Get attribute from tag

<html><!--from  j a va  2s  .  c o m-->
  <head>
    <script src="http://java2s.com/style/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

.attr setter demo

Use attr() to set the attribute value.

<html><!--from j  av  a  2  s . c om-->
  <head>
    <script src="http://java2s.com/style/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

access a property on the first matched element

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

<html><!--from j  a  va2 s .co m-->
  <head>
    <script src="http://java2s.com/style/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><!--from j  a  v  a  2s .  co m-->
  <head>
    <script src="http://java2s.com/style/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><!--from  j a v a  2s  .co  m-->
  <head>
    <script src="http://java2s.com/style/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 value calculation

attr(key, fn) with function

<html><!--  jav  a  2  s  . c  o m-->
  <head>
    <script src="http://java2s.com/style/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

.attr with function return value

Set attribute with the returned function value

<html><!--   j  a v  a 2 s .co  m-->
  <head>
    <script src="http://java2s.com/style/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

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .before()
  2. Add tag before
  3. Add text node before
  4. Insert content before each of the matched elements
  5. Inserts some HTML before all paragraphs
  6. Inserts a DOM element before all paragraphs
  7. Add before and after