Dom
Dom

Reputation: 3126

Find Closest link with jQuery

I have a list of items that looks similar to this:

<ul>
  <li>
    <h3 class="headings"> <a href="page1.html"></a> </h3>
    <div class="details">
      <p>Item Details</p>
      <a href="#" class="linktoitem">Click Here</a> </div>
  </li>
  <li>
    <h3 class="headings"> <a href="page2.html"></a> </h3>
    <div class="details">
      <p>Item Details</p>
      <a href="#" class="linktoitem">Click Here</a> </div>
  </li>
  <li>
    <h3 class="headings"> <a href="page3.html"></a> </h3>
    <div class="details">
      <p>Item Details</p>
      <a href="#" class="linktoitem">Click Here</a> </div>
  </li>

My aim is to add to Click Here linkk from inside h3 inside the same li. HEre is how Im trying to do it:

$('li').each(function(){
    var linkitem = $('.linktoitem').closest('h3').find('a').attr('href');
    $('a.linktoitem').attr('href' , linkitem) 
});

Unfortunately link comes out as undefined.

Any help much appreciated.

Upvotes: 1

Views: 3413

Answers (4)

bcoughlan
bcoughlan

Reputation: 26627

Your problem is that closest only finds ancestors, whereas you're looking for a sibling of the parent:

 var linkitem = $('.linktoitem').parent().siblings('h3').find('a').attr('href')

The other answers are more efficient, but I thought it would be useful to point out your error.

Upvotes: 2

Jos&#233; Carlos
Jos&#233; Carlos

Reputation: 1015

You should do it:

$('li').each(function(){
var href = $(this).children('h3').children('a').attr('href');
$(this).find('.linktoitem').attr('href',href);
})

Upvotes: 1

Jorge
Jorge

Reputation: 18257

Tried like this

$(document).ready(function (){
    $('.details a', 'li').each(function(){
        alert($(this).attr('href'));
    });
});

live example

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You could do:

$('li').each(function(){
    var linkitem = $('h3 a', this).attr('href');
    $('a.linktoitem', this).attr('href' , linkitem) 
});

if my mind reading proved correct: you wanted to achieve this html

<ul>
  <li>
    <h3 class="headings"> <a href="page1.html"></a> </h3>
    <div class="details">
      <p>Item Details</p>
      <a class="linktoitem" href="page1.html">Click Here</a> </div>
  </li>
  <li>
    <h3 class="headings"> <a href="page2.html"></a> </h3>
    <div class="details">
      <p>Item Details</p>
      <a class="linktoitem" href="page2.html">Click Here</a> </div>
  </li>
  <li>
    <h3 class="headings"> <a href="page3.html"></a> </h3>
    <div class="details">
      <p>Item Details</p>
      <a class="linktoitem" href="page3.html">Click Here</a> </div>
  </li>
</ul>

fiddle here: http://jsfiddle.net/79ghE/

Upvotes: 2

Related Questions