Ricardo Binns
Ricardo Binns

Reputation: 3246

get the closest value from a list jquery

i need to get the closest class html from my list, but its always returning null if i put directly the closest. i try some other thinks, but its not working.

the html:

<ul id="ulId">
  <li class='effectLeg'>
    Stuffs
  </li>
  <li class='test legColor' style=''></li>
  <li class='effectLeg'>
    Stuffs 2
  </li>
  <li class='test legColor'></li>
</ul>

so, if i hover the last LI (for exp.) the hover will get the closest class effectLeg and give me the HTML or anything inside ( in that case the STUFFS 2 ).

the js:

$(".legColor").live("hover", function(){
    alert($(this).closest("#ulId").find(".effectLeg").html());
});

the closest i get was using find, but the find only get the first value of my li

i made a exp: check the Demo

Upvotes: 1

Views: 316

Answers (2)

Matt Ball
Matt Ball

Reputation: 359956

.closest() searches the an element's ancestors, but it looks like you're trying to search the siblings. I think you just want .prev():

$(".legColor").live("hover", function(){
    console.log($(this).prev('li.effectLeg'));
});

Demo: http://jsfiddle.net/mattball/nggyX/

Upvotes: 3

Michael Wright
Michael Wright

Reputation: 591

Your syntax is incorrect ... Depending on what closest thing you are after you'd be doing:

alert($(this).closest("ul").html()); 

That would return the html of #ulId

Upvotes: 1

Related Questions