Get and Set attributes using Jquery and .attr()

.attr() in jquery is used to set and get attribute values like class, title etc… from an html element. Below is the syntax for getting and setting values using .attr().

Reading attribute syntax:

.attr( attributeName )

Setting attribute syntax :

.attr( attributeName, value )

In the example below I have tried to demonstrate both reading and setting an attribute value using .attr(). In the example I am setting and getting the “class” attribute. Also I have created jsfiddle for this at http://jsfiddle.net/88NkM/1/.

Example :

$('#yourElementId').attr('title', 'your new title'); // set  
$('#yourElementId').attr('title'); // get  

However, there is a similar attribute called “prop” which can also be used.

Html Code :

<div id="someDiv" class="default" >Some Message</div> <br />  
<div id="redDiv">Make Div Red</div> <br/>  
<div id="greenDiv">Make Div Green</div>  

Jquery Code :

$("#redDiv").click(function(){  
    var currentClassAttr = $("#someDiv").attr("class");  
    console.log("current class attr = " + currentClassAttr);  
    $("#someDiv").attr("class", "red");  
});

$("#greenDiv").click(function(){  
    var currentClassAttr = $("#someDiv").attr("class");  
    console.log("current class attr = " + currentClassAttr);  
    $("#someDiv").attr("class", "green");  
});  

CSS Code :

.default{  
    padding:20px;  
    background:#D6D6D6;  
}

.red{  
    padding:20px;  
    background:#F66666;  
}

.green{  
    padding:20px;  
    background:#66F666;  
}

#redDiv, #greenDiv{  
    cursor:pointer;  
    text-decoration:underline;  
    color:blue;  
}‚Äč

Hope this helps :)