0

I am doing with this plugin :

<table>
<tr>
     <td>
     <a class="linkType1" href="google.com">
         Google
     </a>
     <span style="display: none;">Goooooooooooogle</span>
    </td>
</tr>

<tr>
    <td>
    <a class="linkType1" href="yahoo.com">
        Yahoo
    </a>
    <span style="display: none;">Yaaaaaaaaaaaaaaho</span>
    </td>
</tr>
</table>

How can I select the closest span of linkType1-anchors for displaying as tooltip ?

Currently I am doing :

jQuery(document).ready( function() {
    jQuery("a.linkType1").tooltip({ 
        bodyHandler: function() { 
            alert(jQuery(this).closest("span").html()); // this alert is showing `null`
            return "hi"; // i need to setup the alerted content here
        }, 
        showURL: false 
    });
});
tusar
  • 3,364
  • 6
  • 37
  • 60

3 Answers3

4

Your span elements aren't ancestors of the links, so closest (which looks for a match for the selector on the current element or its ancestors) isn't what you're looking for.

Based on your markup, you might want next("span") (which will find the next sibling, but only if it's a span; it doesn't continue with subsequent siblings) or possibly nextAll("span").first() (which will find the first next sibling that's a span, in case you ever put something between the a and the span), which finds all subsequent siblings with nextAll and then grabs the first of them (the one nearest the link) via first. So

// If the `span` will always be the very next sibling
alert(jQuery(this).next("span").html());

or

// If you may put something between the `a` and the `span` at some point
alert(jQuery(this).nextAll("span").first().html());
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • i think too much vote up... will accept this after 7 minutes. Thanks T.J, thats exactly what I need. +1 – tusar Apr 02 '12 at 08:10
  • could you please look into my another problem ? http://stackoverflow.com/q/8937158/778687 – tusar Apr 02 '12 at 08:10
2

closest() finds the closest parent element. You are looking for a sibling:

jQuery(this).next("span").html()
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • According to the API: Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree. – mamoo Apr 02 '12 at 08:08
  • Parent element or **current** element (if it matches the selector). – Tadeck Apr 02 '12 at 08:08
  • +1 could you please look into my another problem ? http://stackoverflow.com/q/8937158/778687 – tusar Apr 02 '12 at 08:11
0

$(this) is referring to bodyHandler function. Try this

alert(jQuery(linkType1).closest("span").html());

Why not use find() instead? As closest() transverses up the DOM tree

Chibuzo
  • 6,112
  • 3
  • 29
  • 51
  • *"`$(this)` is referring to bodyHandler function"* No, it isn't. The body handler function is called with `this` set to the DOM element (the plug-in, like most, is consistent with how jQuery works). – T.J. Crowder Apr 02 '12 at 08:08