Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text of link that inside td in HTML Table using JavaScript?

I have the following structure of row in my table:

<tr class="mattersRow">
    <td></td>
    <td colspan="16">
        <div class="dropdown">
            <a href="#" data-toggle="dropdown">Choose QB</a>
            <ul class="dropdown-menu" aria-labelledby="dLabel" role="menu"> … </ul>
        </div>
    </td>
</tr>

Note: I use bootstrap library

I need to set to every <td> that has text inside "" (empty), or "Choose QB" class='danger'.

This is my jQuery code:

$("#tblMatters .mattersRow td").each(function () {
      if ($(this).html() == "" || $(this).innerHTML == "Choose QB")
      {
           $(this).addClass("danger");
           flag = true;
      }
});

Of course, $(this).html() == "" works great, but how to set "danger" class to the <td> with Choose QB

like image 561
Bryuk Avatar asked May 08 '26 01:05

Bryuk


2 Answers

You may use :contains()doc and :emptydoc selectors :

$('#tblMatters .mattersRow')
    .find('td:contains(\'Choose QB\'),td:empty')
    .addClass('danger');

Here is a demo : http://jsfiddle.net/wared/a84CW/.

addClass accepts a function as an argument, and within that function you have access to the currently iterated td element, and can check what it contains :

$("#tblMatters .mattersRow td").addClass(function() {
    var txt = $.trim( $('a', this).text() );

    return txt.length === 0 || txt == 'Choose QB' ? 'danger' : '';
});

If you're only trying to check the text inside the anchor, you should specify that in the question ?

like image 41
adeneo Avatar answered May 09 '26 15:05

adeneo