最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery .addclass to table <tr> element where text is found - Stack Overflow

programmeradmin3浏览0评论

I am theming some report tables and do not have access to the templates.

I have this code so far which ends up adding "my-class" to every TR element in the report table. However, I only want to add the class to the table row TR where the text was found. I am thinking I need a little more code to do this. Here are a few things I have tried so far:

if ($('#report-area table tr:contains("Name")', this).length > 0) {
$("#reportArea table tr", this).addClass("my-class");
}

I have also tried:

if ($('#report-area table tr:contains("Name")', this).length > 0) {
$(this).addClass("my-class");
}

... but that did not work either.

I am theming some report tables and do not have access to the templates.

I have this code so far which ends up adding "my-class" to every TR element in the report table. However, I only want to add the class to the table row TR where the text was found. I am thinking I need a little more code to do this. Here are a few things I have tried so far:

if ($('#report-area table tr:contains("Name")', this).length > 0) {
$("#reportArea table tr", this).addClass("my-class");
}

I have also tried:

if ($('#report-area table tr:contains("Name")', this).length > 0) {
$(this).addClass("my-class");
}

... but that did not work either.

Share Improve this question asked Nov 8, 2011 at 20:12 Danny EnglanderDanny Englander 2,0445 gold badges27 silver badges41 bronze badges 2
  • 1 Per Sarfraz' comments, please clarify exactly what it is you mean by "where the text was found". – Blazemonger Commented Nov 8, 2011 at 20:26
  • Agreed with @mblase75 :) – Sarfraz Commented Nov 8, 2011 at 20:30
Add a comment  | 

4 Answers 4

Reset to default 15

Just use the selector with no fluff:

$('#report-area tr:contains("Name")').addClass('my-class');

http://api.jquery.com/contains-selector/

var $rows = $('#report-area table tr');

$rows.each(function(i, item) {

    $this = $(item);
    if ( $this.text() == 'Name' ) {
        $this.addClass('yourClass');
    }

});

I only want to add the class to the table row TR where the text was found.

You can do:

$('#report-area table tr').each(function(){
  if ($.trim($(this).text()).length > 0) {
    $(this).addClass("my-class");
  }
});

You can also use the .filter() function as well here:

$(document).ready(function () {
    $('#report-area tbody tr').filter(function () {
        return $.trim($(this).text()).length > 0;
    }).addClass("my-class");
});

I like this because it's a little cleaner and limits the number of rows you need to iterate over.

发布评论

评论列表(0)

  1. 暂无评论