简体   繁体   中英

Get text from closest span using jQuery

I'm looking to retrieve the text inside a HTML table that is rendered via a webgrid. The text that I want is located inside a div with the class productID . My starting reference point is in the same row but the last td with the class span2 . I'm trying to use jQuery's closest() method however I'm not getting any value returned.

Please see below for a section of the rendered HTML and my jQuery function:

HTML:

<tr>
    <td class="span1"><div class="productID">1</div></td>
    <td class="span2">Listing</td>
    <td class="span2">Full Districtution</td>
    <td class="span2">$1,350.00</td>
    <td class="span2">2016-01-01</td>
    <td class="span2"><div title="This is my brand new title!" data-original-title="" class="priceToolTip">2016-04-30</div></td>
    <td><a href="/product/AddOrEditProduct?productID=1">Select</a></td>
</tr>

jQuery:

$(".priceToolTip").mouseover(function () {
    var row = $(this).closest("span1").find(".productID").parent().find(".productID").text();
    console.log("Closest row is: " + row);
});

The .closest() method looks for a match in the ancestors. So you can use it to grab the tr then look for .productID like so:

var productID = $(this).closest('tr').find('.productID').text();

Or:

var productID = $(this).parent().find('.productID').text();

Or:

var productID = $(this).siblings('.span1').find('.productID').text();

.span1 is not the closest element of .priceToolTip . Use closest("tr").find(".span1 .productID") like following.

$(".priceToolTip").mouseover(function () {
    var row = $(this).closest("tr").find(".span1 .productID").text();
    console.log("Closest row is: " + row);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM