1

I have a table where all my rows are like this:

<tr> 
    <td class="name">name1</td>
    <td class="type">type1</td>
    <td class="edit">
        <a href="edit" class="edit">edit</a>
    </td>
</tr>

I need to disable the edit href for certain types. So I need something like:

row = $('.mytable').find(row where .type value = type_with_no_edit) #this is where I need elp
row.find('a.edit').remove();

If the row was alwasy the first one, I would do:

row = $('.mytable tbody>tr:first')

but that's not always the case.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
duduklein
  • 10,014
  • 11
  • 44
  • 55

2 Answers2

4

Sounds like a job for filter...

$('.mytable tr').filter(function() {
    return $("td.type", this).text() === "type_with_no_edit";
}).find('a.edit').remove();

That finds every row that has the text type_with_no_edit in the td with the class type and removes the td with a.edit that is a sibling.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
  • Edited the code by adding () to text and stricter equality. :) – Henrik Andersson Nov 23 '12 at 13:00
  • Doh! Thanks for spotting that. – Reinstate Monica Cellio Nov 23 '12 at 13:01
  • @limelights FYI `.text()` always return `string` so there is really no need for `===` in this particular case – David Hellsing Nov 23 '12 at 13:09
  • @David yeah, I know but `===` is always a good practice. Read here why http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – Henrik Andersson Nov 23 '12 at 13:11
  • That decision is very individual IMO. I’m just saying that in this case `==` and `===` makes no difference, hence my comment to the edit. – David Hellsing Nov 23 '12 at 13:13
  • Of course , but I'm not really seeing a reason to go with the not as good way if I have the option to choose the right way. The point was to start enforcing a behaviour that is good practice and not lazyness, IMO. :D – Henrik Andersson Nov 23 '12 at 13:17
  • @David That example is even worse. Youre relying on type conversion to convert the array object [] to a string. That is lying to yourself and your code. Fun example though! :) – Henrik Andersson Nov 23 '12 at 13:45
  • @limelights no, Im just comparing `String('a')` with `'a'` using loose type comparison. Just one case where `==` is actually useful. But it’s all in my opinion of course. I personally don’t believe in saying "always use that" or "never use that" in a programming language. – David Hellsing Nov 23 '12 at 13:50
2

You can use the :contains pseudo-selector:

$('td.type:contains("type_with_no_edit")').siblings('.edit').empty();

Demo: http://jsfiddle.net/XLwfs/

If you don’t want to empty the TD, just target the anchor and remove it instead.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212