jQuery Alert / Get DIV Title Examples
If you ever wanted to alert Div title using jQuery but didn’t know how to do it, then you will find this article immensely helpful as I am going to share 2 ways to get div title using jQuery. By using jQuery, get title of any div or paragraph or any other element. Read on to find out more.
How to use jQuery to Get DIV Title / Alert DIV Title
I am going to show you 2 ways to alert / get div title using jQuery. The difference in these two methods is minor and you will be able to understand them very easily. The differences exist primarily due to the version change in jQuery. I am going to show you how to do this by using an easy to follow example. Assume that we have a div with ID “my_div” and it has the title “My Div title”. Our aim is to get div title when “Show DIV title” button is clicked.
Common HTML Source Code for the following examples:
<html> <head> <title>Alert DIV Title using jQuery</title> <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script> </head> <body> <div id="my_div" class="my_class" title="My Div title">This is my div.</div> <input type="submit" name="show_title" id="show_title" value="Show DIV title" /> </body> </html>
Example 1: How to get Div Title when jQuery version < 1.6
<script type="text/javascript">
$(document).ready(function() {
$('#show_title').click(function(){
// Get / Alert Div Title when jQuery version < 1.6
alert( $('#my_div').attr("title") );
});
});
</script>Example 2: How to get Div Title when jQuery version > 1.6
<script type="text/javascript">
$(document).ready(function() {
$('#show_title').click(function(){
// Alert / Get Div Title when jQuery version > 1.6
alert( $('#my_div').prop("title") );
});
});
</script>So if you are using jQuery version > 1.6, I strongly suggest you to go with Example 2 shown above for best practices & for better future compatibility .
Your turn!
Do you know of any other ways to use jQuery to alert / get Div title? Feel free to suggest by commenting below.