Razib
Razib

Reputation: 11153

How to select element if I don't know its id

From this question I have learned how to set dynamic id for the following code snippent -

<c:forEach var="food" varStatus="i" items="${selectedIngredientsList}">
        <c:set var="foodInfo" value="${food.foodItemId}"/>    
        <ul>
            <li id="??"><c:out value="${food.foodName}"/>
            </li>
        </ul> 
</c:forEach>

I can set dynamic id like this (according to kitokid's answer) - <li id="my_${foodInfo}">. This trick work for me. But if I want to get the id from javascript by using id selector how can I achieve this? For static id we can write $('#myId'). Since the id here is dynamic how can I catch the id?

Thanks in advance.

Upvotes: 1

Views: 151

Answers (1)

dfsq
dfsq

Reputation: 193261

You can use other CSS selectors. For example you can bind click event on parent UL element and then handle click event like this:

$('ul').on('click', 'li', function() {
    alert( this.id ); // get click id
});

or

$('li').click(function() {})

will also bind click event to each LI element.

So you don't have to know id of the element to find this element and bind event to it.

Upvotes: 2

Related Questions