简体   繁体   中英

jQuery find text between tags

Disclaimer: Yes, I am aware of the mess this HTML is. It's from a legacy application. Unfortunately, changing HTML is not an option, since it is a large page with many dependencies.

That said, I have the below code:

<tr>
    <th align="left" style="background:#CCCCCC;" nowrap="">
        <a class="ContentLink addLink" id="content">
            <img border="0" src="/tools/images/buttons/restore.gif" alt="edit (popup)">Add
        </a>
    </th>
    <th colspan="3" nowrap="" width="100%">
        <font id="maroon">Associated Computer(s)</font>
    </th>
</tr>

Using jQuery, I would like to get the string between the font tags "Associated Computer(s)".

I've tried using jQuery's find and next APIs, but it's not working as I expect.

I've tried var myHeader_next = $(this).find("font"); and it returns an object. When I use var myHeader_trim = $.trim(myHeader_next); , I get [object Object] .

I've tried var myHeader_next = $(this).find("font").text(); and var myHeader_trim = $.trim(myHeader_next); and for both, I get blank responses.

$(document).ready(function () {
    $(".addLink").click(function(){
        var SR_ID = $("#SR_ID").val();
        var myHeader_next = $(this).find("font").text();
        var myHeader_trim = $.trim(myHeader_next);
        console.log(myHeader_next);
        console.log(myHeader_trim);
    });     
});

I have a feeling I'm not understanding find and next correctly, but don't know why.

You can use .html().

$('#maroon').html()

returns

Associated Computer(s)

The easiest way to find it would be:

var myHeader_next = $(this).closest("tr").find("font");

That will travel up the DOM change until it finds the first ancestor <tr> and then .find("font") finds all of the <font> tags in the <tr> tags descendants.

At that point, you should have the correct <font> element that you are looking for and .text() will work.

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