<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
Here I have a table with a tr
in it and 4 td
's.
Now, my question is, how can I compare the td.text()
with the other one?
For example:
a loop that takes the text of first td
and then compare it with other td
's.
If it is the same, then give that td
a class.
HERE: td id="td1"
should get a class
BUT:
When I'm at the 3e td
, the 3e td
should get a class.
You can use this code:
If I understand correctly, you want to select the first 'td' in a 'tr' and compare it against the other 'td' in your table. Please try the below code and let me know if it works for you.
HTML (provided by OP)
CSS
jQuery
I tried to keep it as simple as possible. The variable first pertains to that first 'td' that you want to use for comparison. Note how the each function operates on 'all elements except the first child in the tr', which clearly will omit the first variable we declared initially. From there it's all about comparing using $(this).html() to grab the value of the currently selected element, against the value obtained from the first variable.
Once this succeeds, simply add a class of your choice. For simplicity's sake, I added my own color--red class to the mix, which should show red color text for the third 'td' element as you suggested in your question post. Enjoy! Let me know if you need anything further.
This code should work for you:
FIDDLE: https://jsfiddle.net/lmgonzalves/cqa6m6va/1/
jQuery selectors will be your friend here. :)
I'll explain the logic, and then touch on one issue to be aware of . . .
Basically, this code:
<tr>
and loops through them one at a time<tr>
that contain that same text value<tr>
contain that text, all of those children are given the class of "td"The one potential issue that this solution could run into is if the text in the current element is present as part of the text in one of its siblings. For example, if the text in one sibling is "the", and it has some siblings that have text values of "then" and "there" and "the end", they will be found by
:contains
.If your text values are sufficiently "patterned" (as they are in your example), though, this should not be an issue. If it is an issue, there is a more complex way to do that "common text" selection, but I won't bother with that, unless it is necessary.