Lucio Paoletti
Lucio Paoletti

Reputation: 371

jQuery, next() or prev() or other that don't I know?

i have this lists, and i want select li element from jquery when the link is click

<ul>
    <li><a class="accordion" href="#">1</a></li>    
    <li><a class="accordion" href="#">2</a></li>    
    <li><a class="accordion" href="#">3</a></li>    
    <li><a class="accordion" href="#">4</a></li>    
    <li><a class="accordion" href="#">5</a></li>    
    <li><a class="accordion" href="#">6</a></li>    
</ul>

i write this jquery code

 $('a.accordion').click(function() {
      var href = $(this).attr("href");
      div = $('<div/>', {
         id: 'intotheli',
         style: {width:200}
      });
      //console.log(div);

      // loading content  with ajax custom function  
      div.html( loadcontent(div,$(this).attr("href"))); 
      // on this point i want find the li tag that contain the clicked link
      div.slideDown('slow').appendTo($(this));                  

      return false;
});

i have tried with .next() and prev() from $(this) but i don't resolve my issue (maybe i used them wrong )

Thanks in advance.

Upvotes: 0

Views: 82

Answers (2)

Rich Bradshaw
Rich Bradshaw

Reputation: 72975

As it looks like you are new to this, here's how I'd rewrite this:

<ul class="accordion">
    <li><a href="#">1</a></li>    
    <li><a href="#">2</a></li>    
    <li><a href="#">3</a></li>    
    <li><a href="#">4</a></li>    
    <li><a href="#">5</a></li>    
    <li><a href="#">6</a></li>    
</ul>

This makes the markup smaller and tidier.

Then instead of:

$('a.accordion').click(function() {

I'd use:

$('.accordion').on("click", "a", function() {

This means only one eventhandler is bound, rather than 6, speeding things up a little, but again just keeping things simple. This change only works with my new markup.

The rest of your code will work as is, $(this) still refers to the clicked link.

To get the li element that the a is in, you use $(this).parent('li').

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227240

.next() and .prev() traverse siblings. They get the next/previous sibling. If you want to get the <li> from the <a>, you want .parent.

$('a.accordion').click(function() {
    var $li = $(this).parent('li');
});

Upvotes: 1

Related Questions