1

I have this code fragment in HTML

<ul class="orderedList">
    <li class="il l1">Appathon 2k14</li>
    <li class="il l2">Da Vinci Code</li>
    <li class="il l3">Java Beans</li>
    <li class="il l4">Gigabyte Wars</li>
    <li class="il l5">Spin A Web</li>
</ul>

I was having event handlers for each list item in my jquery script like this :

$(".l1").click(function x() {
    alert("Description : \n " + eventsDescription[0] + "\n\nLocation : \n" + loc[0]);
});
$(".l2").click(function x() {
    alert("Description : \n " + eventsDescription[1] + "\n\nLocation : \n" + loc[1]);
});
$(".l3").click(function x() {
    alert("Description : \n " + eventsDescription[2] + "\n\nLocation : \n" + loc[2]);
});
$(".l4").click(function x() {
    alert("Description : \n " + eventsDescription[3] + "\n\nLocation : \n" + loc[3]);
});
$(".l5").click(function x() {
    alert("Description : \n " + eventsDescription[4] + "\n\nLocation : \n" + loc[4]);
});

Now I was thinking to optimize my logic like this :

$(".il").click(function x() {
    alert($(".il").attr("class"));
});

As 'il' is a class present in each tag (list item) , when I click on any list item then it should return me the name of the class. My problem is that when I click on any list item, I get result in alert dialog as 'l1 il'.

According to my code, I think I should get 'l2 il' by clicking on second item and so on for rest of the items.

2 Answers 2

5

You should use the $(this) reference,

$(".il").click(function x() { alert($(this).attr("class")); });

In your code you are invoking .attr() over an element collection, that results in retrieving the class names of the element which is present at the 0 index in that collection.

Sign up to request clarification or add additional context in comments.

1 Comment

this is second time, you are beating me to it today!
0

Aravind code is write. u want another option try this

$(".orderedList li").click(function() { alert($(this).attr("class")); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.