This tutorial shows how to get the attribute value of a clicked item with jQuery, any attribute which is added in that HTML tag (id, class, name, title, src, etc.).
- To get the attribute value of an element with jQuery, it is used attr() function.
Syntax:
$(element).click(function(){ var attrval = $(this).attr('attribute_name'); });Now, here's some code, and examples.
$('.class').click(function(){ var id = $(this).attr('id'); });
$('.class').click(function(){ var title = $(this).attr('title'); });
$('.class').click(function(){ var name = $(this).attr('name'); });
Click on this image: <img src="imgs/webcourses.gif" alt="Courses: coursesweb.net" class="imgs" id="the_id" width="180" height="60" /> <script type="text/javascript"><!-- $(document).ready(function() { $('.imgs').click(function(){ var idimg = $(this).attr('id'); var srcimg = $(this).attr('src'); alert('ID is: '+ idimg+ '\n SRC: '+ srcimg); }); }); --></script>Demo:
$('#id').click(function(){ var class = $(this).attr('class'); });
$('#id').click(function(){ var name = $(this).attr('name'); });
Click on this image: <img src="imgs/webcourses.gif" alt="Courses: coursesweb.net" class="clsimg" id="idimg" width="180" height="60" /> <script type="text/javascript"><!-- $(document).ready(function() { $('#idimg').click(function(){ var classimg = $(this).attr('class'); var altimg = $(this).attr('alt'); alert('Class: '+ classimg+ '\n Alt: '+ altimg); }); }); --></script>Demo:
$('div').click(function(){ var id = $(this).attr('id'); });
$('p').click(function(){ var class = $(this).attr('class'); });
$('input').click(function(){ var name = $(this).attr('name'); });
<div id="idiv" class="clsdiv">Click on this text:<br/> Free Web Programming Courses - https://coursesweb.net/</div> <script type="text/javascript"><!-- $(document).ready(function() { $('div').click(function(){ var idd = $(this).attr('id'); var classdiv = $(this).attr('class'); alert('ID is: '+ idd+ '\n Class: '+ classdiv); }); }); --></script>Demo:
$('*').click(function(){ var id = $(this).attr('id'); });
<link href="/templ/style.css" rel="stylesheet" type="text/css" />
h2 { font-size: 1em; }
document.getElementById("someID").innerHTML = "HTML content";
$str = "http://CoursesWeb.net/"; $nr_chr = strlen($str); echo $nr_chr; // 22