views:

93

answers:

5

I have a span and an anchor inside a table cell. I have the anchor set up to show a tooltip. I would like the text inside the span to be used for the tooltip. How can I select this text in jQuery?

  <td class="row-head" colspan="5"><span class="tip-text">Complete Coverage</span><a href="#" class="help"></a></td>

JQuery code - the current selector always finds the first instance only for all tips.

$(document).ready(function() {
  $('.help').qtip({ style: { name: 'cream', tip: true },
                 content: {
                 text: $(this).find('span.tip-text').html() 
   } });
});

Thanks

A: 

I will confess to having not tested this (yet), but this should fetch the span contents, you can iterate this for each row in your table.

$('a.help').siblings('.tip-text').text();
Duncan
`closest()` won't help as the `.tip-text` is a sibling of the `.help` not a parent.
gnarf
Ta, wasnt thinking!
Duncan
Thanks Duncan for the final piece! Thanks to everyone who answered, the iteration was def the key..
Jakey
A: 
$(document).ready(function() {
    $('.help').qtip({ 
        style: { name: 'cream', tip: true }, 
        content: { text: $(this).parent().find('span.tip-text').text(); }
        }); 
});

Although I would just suggest using the anchor's title attribute like so

<a href="#" class="help" title='Complete Coverage'></a>

and qtip will automatically use that as the tooltip

Jimmy
A: 

$(this).parent().find('span.tip-text'); Find just looks for descendants of the selected element, I think.

http://api.jquery.com/find/

Paul Huff
+2  A: 

The problem is your use of this. I recently ran into the same thing where I assumed that $('some-selector').whatever() implied a loop over all matching objects.

In fact, it doesn't. this is not referring to the current element with a class of help.

If you really need to do something based on the current matching element, you need to use the each() function like this:

$('.help').each( function(idx) {
    $(this).qtip({ 
        style: { name: 'cream', tip: true },
        content: { text: $(this).find('span.tip-text').html() } 
    });
});
Mark Biek
That each is going to break because you are attaching the qtip to all `.help` again instead of using `$(this).qtip()`
gnarf
Thanks :). Fixed
Mark Biek
+4  A: 

Your problem is that $(this) is being evaluated in the document ready functions context, you can use the .each() function to iterate over each .help. The function you are looking for to find the .tip-text could easily be .prevAll() or .siblings().

$(document).ready(function() {
  $('.help').each(function() {
     // iterate over each .help, find its span.tip-text and create the qtip
     $(this).qtip({ 
       style: { name: 'cream', tip: true },
       content: {
         text: $(this).siblings('span.tip-text').html() 
       } 
     });
  });
});
gnarf
Thanks for your help!
Jakey