Wednesday, August 13, 2014

Handling Attributes of an Element in JQuery

INTRODUCTION

Attributes define the actual element's style, id etc for any element. For example, element <div> will have attributes like.
  • id
  • style
  • align
  • lang
  • title
Now we will see how can we get the existing value of these attribute and also how to reset the values by the following example.

Example Program

attributes.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Attributes Setter/Getter</title>
</head>
<script type="text/javascript" src="lib/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/attributes.js"></script>

<body>
 <div id="myDiv" style="background: red; width: 200px" align="left" lang="en" title="MySampleDiv">MyDivContent</div>
 <input type="button" id="btn" value="Attributes" />
 <br>
 <br>
 <table border="1">
   <tr>
     <td id="td1"></td>
     <td id="td2"></td>
     <td id="td3"></td>
     <td id="td4"></td>
   </tr>
 </table>

</body>
</html>

attributes.js
$(document).ready(function() {
 $("#btn").click(function() {
   // Get the existing attribute values
   $("#td1").text($("#myDiv").attr("style"));
   $("#td2").text($("#myDiv").attr("align"));
   $("#td3").text($("#myDiv").attr("title"));
   $("#td4").text($("#myDiv").attr("lang"));

   // Reset the existing attribute values
   $("#td1").text($("#myDiv").attr('style', 'background:blue'));
   $("#td2").text($("#myDiv").attr("align", 'right'));
   $("#td2").text($("#myDiv").attr("title", "NewDivValue"));
   $("#td2").text($("#myDiv").attr("lang", "jp"));

 });
});

No comments :

Post a Comment