3

I have this markup:

<div class="news-listItem">
     <p class="date">Date: 06.03.2012</p>
     <h2><a href="#">test aaaaa</a></h2>
     <div class="news-content">Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum</div>
     <a href="#" class="read-more">Read more</a>
</div>

I want to get the read more button based on the div class="news-content". My jQuery code looks like this:

$('.news-content').closest('a.read-more').on('click', function(){
// code here
});

But this is not working. I have multiple posts on a page so I can not do $('a.read-more').

1
  • 1
    Just use .next() if it always going to be next item. $('.news-content').next().on('click', function(){...}); Commented Mar 6, 2012 at 20:32

3 Answers 3

6

.closest() traverses up the DOM tree. What you need is .next():

$('.news-content').next('a.read-more')
5

The closest[API] method gets an ancestor. You need the siblings[API] method.

$('.news-content').siblings('a.read-more').on('click', function(){
// code here
});
12
  • While user zerkms suggested .next() works, I'd prefer the use of .siblings() as more general, looking in both ways. +
    – kontur
    Commented Mar 6, 2012 at 20:28
  • 1
    @kontur: it depends on the task. There is no reason in programming to do more work than it is required. "General" is not synonymous to "better"
    – zerkms
    Commented Mar 6, 2012 at 20:29
  • Certainly. In real world use I sometimes found myself looking for errors because manipulating the DOM would cause the object not to be .next() or .prev() any more - personally, I find it more easy to think of which level of the DOM I am in, not necessairly, if to look ahead or back on that level. But you are absolutely right, it is merely a personal/situational preference, both answers are equally valid.
    – kontur
    Commented Mar 6, 2012 at 20:33
  • I would argue that siblings is slightly more future-proof than next with no added programming cost, because as long as the elements remain at the same DOM level, it works. next is more brittle. Execution cost may differ, but I bet it's similar or negligible. In the end, both siblings and next are sufficient solutions given the context, so the OP can decide which fits best. Commented Mar 6, 2012 at 20:40
  • 1
    @zerkms Yes, both would fail in that case, but if another element were inserted between the <div> and the <a> (another common change), next would fail and siblings would not. In my opinion, that makes it a better choice. Commented Mar 6, 2012 at 21:00
0

You can use CSS selectors:

$('.news-content+a.read-more').on('click', function(){
    // code here
});

I think it's better, because modern browsers support the native search for the selector.

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