How to set attribute of any element in jquery

Sometimes it becomes our requirement to set the attribute of any element using jquery. For instance, in my next tutorial i will teach you how to set the alt attribute of images that doesn't contain the alt attribute. Its very easy in jquery by using its attr() function which is built-in in jquery.Let's have a look over the example given below.
How to set attribute of any element in jquery

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.divclass{
font-family:verdana;
font-size:12px;
color:green;
}
</style>
</head>
<body>
	<div id="myDiv">Welcome to nice-tutorials.blogspot.com</div><br/>
	<span></span>
<script language="javascript" type="text/javascript">
$("#myDiv").attr('class', 'divclass');
</script>
</body>
</html>

Output:-
Welcome to nice-tutorials.blogspot.com

In the above mentioned code snippet i have decalred a css class which is divclass and then by using built-in attr() function of jquery i assigned divclass to the div having id of myDiv. Using this behavior of attr() function we can set one or more attributes for the set of matched elements.

So that's it.

I love your feedback.

0 comments: