tags:

views:

28

answers:

2

hey guys, i have a rather (for me) complicated task with jquery.

i want to scan an entire table for its th elements. if a th element has a ATERISK (*) in it, i want to hightlight the the parent, which is the tr element.

i know it sounds complicated when i explain it :)

so imagine i have a dynamic html table where i want to enable a feature to higlight certain rows. therefore i just want to put some symbol (in my case an Aterisk *) to some text inside of a table cell. if jquery detects a aterisk inside of th it should automtically give its parent() a classname!

a start would be probably an each function:

$(function() {
    $("table tr th").each(function() {
        $(this).parent().addClass("special");            
    });
});

but i have no idea how to scan for the aterisk!?

thank you for your help!

+3  A: 

This could help:

$(function() {
    $("table tr th").each(function() {
        if ($(this).text().indexOf('*') > -1)            
            $(this).closest('tr').addClass("special");            
    });
});

EDIT: You'd probably want the th itself to have a special class as in the demo here

Floyd Pink
awesome thank you!
do have also an idea how i could remove the aterisk afterwards? so it's just there to know which th/tr should be special, but i don't want to actually show it in the table. is there a string-remove method in jquery?
Again, you would only need the native JavaScript `.replace()` for this - http://www.w3schools.com/jsref/jsref_replace.asp`$(this).addClass("special").text($(this).text().replace('*',''));`
Floyd Pink
awesome. i tried with replace but couldn't quite figure it out. thank you so much!
+1  A: 

Here's a simpler way:

$("table tr th:contains('*')").parent().addClass("special");

Example at jsfiddle.

Edit from reading OP's comment:

In order to remove the asterisk, you'll need to iterate over the found elements:

$("table tr th:contains('*')").each(function(){
  var $This=$(this);

  $This.parent().addClass("special"); /* Add the "special" class */
  $This.text($This.text().replace("*","")); /* Remove the asterisk */
});

Example with asterisk removal.

Gert G