0

I have a list that I want to attach a click onto for each li although i'm failing to get this working, example below. please help!? Thanks,

 <ul>
   <li>a</li>
   <li>b</li>
   <li>c</li>
   <li>d</li>
 </ul>


 $('li').each(function () {
     $(this).click(function (e) {
        // access the letter - not sure how to do this (?)
     });
  });
1

2 Answers 2

1

Just do:

$(function(){
     $('li').click(function (e) {
        alert(this.innerHTML);  // not sure how to access this (?)
     });
});

You don't need to use each iteration on li. All you need is a selector while registering the click event and then access either with plain element propert this.innerHTML or jquery methods $(this).text() or $(this).html()

Demo

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

6 Comments

for some reason the alert pops up multiple times?
@Aiias this is not jquery object $(this) is.
@Aiias this by default is not a jQuery object
@JamesRadford added a fiddle. See if that help you.
@JamesRadford - is your code wrapped in a document ready call?
|
0
$('li').click(function (e) {
    $(this).text(); 
 });

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.