jQuery Set Title of Div, Image or any element when button is clicked
If you ever wondered how to set title of Div, Image or any element when button is clicked using jQuery, then this article is for you. In this article, I am going to show with examples, how easy it is to set the title of an image, a div or any other element using jQuery. Read on to find out more.
Examples to Set Title of Div, Image or any element when button is clicked using jQuery
Let’s assume that we have a div with ID “my_div” and we want to set title of this div to a new value and alert the old and new values, when a button is clicked. Here is how we can use jQuery to set div title:
Example: Full source code to set title of an element (div, image, etc.) when button is clicked using jQuery
<html>
<head>
<title>jQuery Set Title of Div, Image, any element when button is clicked</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<div id="my_div" title="My DIV title">This is my existing div.</div>
<input type="submit" name="sbt_get_title" id="sbt_get_title" value="Set Div Title & Get It">
<script type="text/javascript">
$('#sbt_get_title').on("click", function(){
var title_old = $('#my_div').attr('title');
$('#my_div').attr('title', 'This is a NEW TITLE for my div.');
var title = $('#my_div').attr('title');
alert( 'Div Old Title is: '+ title_old + '\n'+
'Div New Title is: '+ title );
});
</script>
</body>
</html>When you run the code, click on the button to instantly set the div title to the new one and then alert both the old and new div titles. You can simply change the selector in the jQuery code and replace it with an image’s ID or class to alert it’s corresponding title. You can apply the same procedure to set title of a div, image or any other element.
Simple, isn’t it?
Do you know of any other ways to set title of an Image, Div or any element when button is clicked? Feel free to suggest by commenting below.