JQuery, find the class name li (inside ul)

I have ul with the number li inside. Does everyone have id "# category", but different classes (for example, ".tools", ".milk", ".apple").

Using jQuery. I:

$("li#category").click(function(){ some_other_thing ( .... )}); 

now I need to put the class li "name" - (indeed, a string) inside some_other_thing () function instead of ....

How can I do that?

+6
javascript jquery
source share
5 answers
 $(this).attr('class') 
+8
source share

The identifier must be unique in the document, therefore the presence of several <li> elements with the identifier "category" is invalid. Change this to a class or data attribute or something else. Or just assign the class to the parent <ul> so you can easily get all the li inside it.

 <ul id="categories"> <li class="tools"> <li class="milk"> </ul> 

Get all li and assign a click handler.

 $('#categories li').click(function() { var className = $(this).attr('class'); some_other_thing(className); }); 
+4
source share

Beware that id must be unique! You assume that every li element has the same id . You might want to replace it with a class , for example:

 <ul> <li class="category tools" /> <li class="category milk" /> </ul> 

Then select with:

 $('li.category').click(function(){}); 
+3
source share

Li elements must have unique identifiers. Once they do this, you can select all the li ul files with the ">" operator:

 var ul_elem = $("#id_of_ul"); $("> li", ul_elem).click(...); 

OR

 $("#id_of_ul > li").click(...); 

OR

 $("ul.classname > li").click(...); 
+1
source share

If I understand this correctly, the problem is that you cannot have multiple lithiums with the same identifier. You can only have one unique identifier per page. You probably need to change the identifier to a class. So you will have something like that.
<ul>
<li class="category milK">Chocolate</li>
<li class="category tool">Big Hammer</li>
</ul>

Then you can search using $("li.category").click(function() {....});

0
source share

All Articles