I have ul with a number of li inside. All li have an id "#category" but different classes (like ".tools", ".milk", ".apple").
Using jQuery. I do :
$("li#category").click(function(){ some_other_thing ( .... )});
now i have to put a li's class "name" — (a string indeed) inside the some_other_thing() function instead of ....
How it can be done?
I have ul with a number of li inside. All li have an id "#category" but different classes (like ".tools", ".milk", ".apple").
Using jQuery. I do :
$("li#category").click(function(){ some_other_thing ( .... )});
now i have to put a li's class "name" — (a string indeed) inside the some_other_thing() function instead of ....
How it can be done?
Share Improve this question edited Aug 30, 2010 at 22:29 There Are Four Lights asked Aug 30, 2010 at 22:24 There Are Four LightsThere Are Four Lights 1,4263 gold badges20 silver badges35 bronze badges5 Answers
Reset to default 8$(this).attr('class')
Beware that id
must be unique! You're suggesting that each li
element has the same id
. You might want to replace it with a class
, e.g.:
<ul>
<li class="category tools" />
<li class="category milk" />
</ul>
Then select with:
$('li.category').click(function(){});
ID's have to be unique in a document, so having multiple <li>
elements with the id "category"
is invalid. Change that to a class or a data attribute or something else. Or just assign a class to the parent <ul>
so you can easily retrieve all li's inside it.
<ul id="categories">
<li class="tools">
<li class="milk">
</ul>
Get all li's, and assign the click handler.
$('#categories li').click(function() {
var className = $(this).attr('class');
some_other_thing(className);
});
Your li elements need to have unique IDs. Once they do, you can select all li children of the ul with the ">" operator:
var ul_elem = $("#id_of_ul");
$("> li", ul_elem).click(...);
OR
$("#id_of_ul > li").click(...);
OR
$("ul.classname > li").click(...);
If I understand this correctly, the problem is that you cannot have multiple li's with the same ID. You can only have one unique ID per page. What you probably want is to change the ID to class. So you'd have something along these lines.
<ul>
<li class="category milK">Chocolate</li>
<li class="category tool">Big Hammer</li>
</ul>
Then you can search with $("li.category").click(function() {....});