vikramaditya234
vikramaditya234

Reputation: 1408

unable to attach click event to li element using jquery

I am unable to get the click event for this HTML:

<ul id="frd_overlay_list">
<li><div class="divLink"><div id="1"><img src="path"><div class="frdName">Name</div></div></div></li>
<li><div class="divLink"><div id="2"><img src="path"><div class="frdName">Name</div></div></div></li>
</ul>

and JQuery script:

$('li').click(function(){
    console.log('Not working');
});

I am able to get click event for the ul element i.e.

$('ul#frd_overlay_list').click(function(){
    console.log('This works');
});

I have tried this, but this also doesnt work:

$('ul#frd_overlay_list li').click(function(){
    console.log('Doesn't work either');
});

Please give me pointers what am I doing wrong?

Upvotes: 0

Views: 8764

Answers (1)

Vimalnath
Vimalnath

Reputation: 6463

All your example works except for the last one: You need to escape the ' or use double quotes for the string

$('ul#frd_overlay_list li').click(function(){
    console.log("Doesn't work either");
});

Since you want to apply the click events for dynamically added elements, you could use on function of jQuery.

  • on would bind event handlers for dynamically added elements
  • bind would only bind event handlers for currently existing elements.

Usage of on:

$("ul#frd_overlay_list li").on("click", function(){
  console.log("Doesn't work either");
});

Fiddle

Upvotes: 3

Related Questions