Friday, May 11, 2012

jQuery: .attr()

When attr() is called with two parameters, it's used to change the value of the attribute. The first parameter is the attribute, the second parameter is the new value. It attr() is called with one parameter, it's used to get the value of the attribute.

Example:
jQuery: .attr()


<!doctype html>
<head>
 <title>Mobile-Web-App: jQuery, .attr()</title>
 <meta charset="utf-8">
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
 <script type="text/javascript">

  $(document).ready(function(){
  
   //get value of attr "class"
   var myattr = $("#p1").attr("class");
   $("#p1").text("my class is: " + myattr);
   
   //change value of attr "class"  
   $("#p1").attr("class", "newclass");
   
   //get updated value of attr "class"
   myattr = $("#p1").attr("class");
   var oldmsg = $("#p1").text();
   $("#p1").html(
    "<p>" + oldmsg + "</p>" + 
    "<p>" + "my new class is: " + myattr + "</p>");

  });
 </script> 
 
</head>
<body>
<p><b>Mobile-Web-App: jQuery, .attr()</b></P>
<p class="myclass" id="p1"></p>
</body>
</html>


No comments:

Post a Comment