Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .addclass to table <tr> element where text is found

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.

like image 536
Danny Englander Avatar asked Nov 08 '11 20:11

Danny Englander


People also ask

What is addClass and removeClass in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How do you check if an element contains a class in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

Which jQuery DOM method is used to insert content before the selected elements?

The insertBefore() method inserts HTML elements before the selected elements.


1 Answers

Just use the selector with no fluff:

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

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

like image 152
Blazemonger Avatar answered Nov 14 '22 23:11

Blazemonger