upon clicking on any of the li element , i want to get the class name of the link ('a' element) in the alert box. For example, clicking on 'One' will show 'm' and for the 'two', it will be 'n';
html:
<ul>
<li ><a class="m">One</a></li>
<li><a class="n">Two</a></li>
</ul>
javascript:
<script type="text/javascript">
var my_func=function(){
var link_class; // find this class name
alert("link class name ="+ link_class);
};
$(document).ready(function(){
$('ul li').click(my_func);
});
</script>
How can I find the value of the variable 'link_class' using jquery?
var my_func = function(){
var link_class = $(this).find('a').attr('class'); // find this class name
alert("link class name ="+ link_class);
};
$('ul li').click(my_func);
or in a shorter way, without using new variables for the expression function
$('ul li').click(function() {
var link_class = $(this).find('a').attr('class'); // find this class name
alert("link class name ="+ link_class);
});
<script type="text/javascript">
var my_func=function(){
var link_class; // find this class name
link_class = $(this).children('a').attr('class');
alert("link class name ="+ link_class);
};
$(document).ready(function(){
$('ul li').click(my_func);
});
</script>
assumed
that since he has a
elements inside the li
, by clicking the a
jQuery's this
would be considered the a
and not the li
. But since he is using a
simply to find the class name (assuming
again they are dead links or # links) then he will need to ensure he uses preventDefault()
for those a
tags. If they are "dead links" then I would suggest he uses <span>
instead and just CSS them to look like links, if that's the style he was wanting to achieve - JT Smith 2012-04-05 03:27
$("li a").click(function(){
alert($(this).attr('class'));
});
a
element. The most it has is siblings, but that would return all similar classes of sistera
tags withing the element, not the element for which he clicked - JT Smith 2012-04-04 07:44