find the class name of the link under a 'li' using jquery

Go To StackoverFlow.com

0

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?

2012-04-04 07:39
by Istiaque Ahmed


2

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);
});
2012-04-04 07:41
by fcalderan


0

<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>
2012-04-04 07:42
by trickyzter
children won't work, in his code there is no children of the a element. The most it has is siblings, but that would return all similar classes of sister a tags withing the element, not the element for which he clicked - JT Smith 2012-04-04 07:44
I think you'll want to revoke that comment. My method looks for an anchor tag that is a direct child of the li element clicked. Upon which it sets the variable link_class to the class attribute of the anchor - trickyzter 2012-04-04 08:52
Yes you are correct, I must have read his question too quick, I 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


0

$("li a").click(function(){
    alert($(this).attr('class'));
});
2012-04-04 08:38
by manishbagra
that is right.The question is a part of a real time problem. For some reason, i can't use the selection u suggested - Istiaque Ahmed 2012-04-04 09:30
Ads