Working with jQuery Selections

  • The common operations of jQuery are getters and setters.
  • They get/set the HTML attributes, CSS styles, element content or element geometry.

Chaining

  • Single method attr() is used as getter and setter. If any value is passed it sets or gets that value.
  • attr(varname, value) acts as a setter. attr(varname) is used to get (return) the value.
  • Setting and getting by using a single method is called method chaining.

Getters and Setters

Setter syntax:
attr(varname,value)
Passes a value to the attr() method.

Getter syntax:
attr(varname)
No value is passed to the attr() method.

Example : Demonstrating for attr() method as Getter

<html>
<head>
<title>getter</title>
     <script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
     </script>
     <script type="text/javascript" language ="javascript">
     $(document).ready(function()
     {
          var title =$("em").attr("title"); //getter
          $("#divid").text(title);
     });
     </script>
</head>
<body>
     <div>
          <em title="Learn jQuery"> Introduction </em>
          <p id="myid"> First program </p>
          <div id="divid"></div>
     </div>
</body>
</html>


Output:
Introduction
First program
Learn jQuery

Example : Demonstrating for attr() method as Setter

<html>
<head>
<title>setter</title>
     <script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
     </script>
     <script type="text/javascript" language ="javascript">
     $(document).ready(function()
     {
     $     ("table").attr("border", function(arr)
          {
               return arr;
          });
     });
     </script>
</head>
<body>
     <table><tr><td>BE</td></tr></table>
     <table><tr><td>MCA</td></tr></table>
     <table><tr><td>MBA</td></tr></table>
     <table><tr><td>PGDM</td></tr></table>
</body>
</html>


Output:
attr method