0

I'm attempting to use .closest to grab the closest <li> value based on clicking one of the <li> elements. I'm not having much luck. First off, I'm not having much luck trying to figure out how to add the .click part to the .closest.

Thanks in advance.

 <script>

 $(document).ready(function() { 



 var test = $('#test').closest('li').text();

 alert(test);

 });
</script>
</head>
<body>
<tbody>


<ul id="test">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
3
  • 4
    Accept some answers in your previous questions.
    – amosrivera
    Commented Mar 13, 2011 at 17:52
  • 2
    Side note: I see that you use a tbody element in the body element, that is not correct. A tbody element is only used as a child to a table element.
    – Guffa
    Commented Mar 13, 2011 at 17:57
  • closest() looks for the closest parent, not children of the element. Use children() for immediate children or find() for any children of the element.
    – Mottie
    Commented Mar 13, 2011 at 18:09

1 Answer 1

1

To hook up the onclick event you use the click method and provide a function as event handler:

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

In the event handler you can use this to access the element that was clicked on:

var test = $(this).text();

As you are getting the text inside the element, you don't want to use the closest method as that is used to find a different element (specifically a decendant element).

So:

$(function() { 

  $('li').click(function() {
    var test = $(this).text();
    alert(test);
  });

});
4
  • Thanks for the post! I'm trying to apply it this way without any success. Where am I messing up? $(function() { $('.vote').click(function() { var vote = $(this).text(); alert(vote); }); }); }); <span class="vote">Vote</span> Commented Mar 13, 2011 at 21:27
  • @user550495: You have one too many }); in that code. Here is a working example: jsfiddle.net/k8EvB
    – Guffa
    Commented Mar 14, 2011 at 7:34
  • That works great! However, what i'm trying to do is get a unique value identified with the vote text. Ie <span class="vote" id="123456"> i want to grab that Id so i know what to pass to the db. Any thoughts? Commented Mar 15, 2011 at 2:16
  • @user550495: You can get the id of the clicked element using $(this).attr('id').
    – Guffa
    Commented Mar 15, 2011 at 13:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.