Meules
Meules

Reputation: 1389

select any tr and/or td and hide an element

I tried to find an answer here but can't get this done!

I have a table with a few rows. Some have a name in a cell others an upload id. Like so:

<tr>
 <td>blabla</td>
 <td>Name: Messi</td>
 <td><a id="upload-button" href=".."/>button</a></td>
 <td>blabla</td>
</tr>
<tr>
 <td>blabla</td>
 <td>upload id: 123456</td>
 <td><a id="upload-button" href=".."/>button</a></td>
 <td>blabla</td>
</tr>
<tr>
 <td>blabla</td>
 <td>upload id: 654321</td>
 <td><a id="upload-button" href=".."/>button</a></td>
 <td>blabla</td>
</tr>

I'm trying to find every td with name in it. Just the word name and not name: messi. If that word is present then hide the #upload-button in the next td. I really can't figure that one out.

What I have is this and both don't work. Can anybody help me with this??

$('tr:has(td:contains("name"))').closest('#upload-button').hide(); //doesnt work


    $("tr td:contains('name')").each(function(){
      $(this).siblings('td').css("visibility","hidden");
    });//doesnt work

Upvotes: 0

Views: 65

Answers (2)

TheGr8_Nik
TheGr8_Nik

Reputation: 3200

You can try with the following:

$('td').each(function(){
    //check if contains 'name'
    if( this.innerHTML.toLowerCase().indexOf( 'name' ) !== -1 ) {
        // I think next is better as siblings -> selects only the button td
        //$(this).siblings('td').css("visibility","hidden");
        $(this).next('td').css("visibility","hidden");
    }
});

EDIT Added .toLowerCase() based on the comments ;-)

Upvotes: 2

Jamiec
Jamiec

Reputation: 136094

A bit of creative filtering and finding.

$(function(){

     $('tr td').filter(function(){
        return $(this).text().toLowerCase().indexOf('name')>-1;
      }) // first find only the td's containing the text you want
      .parent() // step up to the tr
      .find('a') // find the `a` - only because you've duplicated id's. This could be any selector
      .hide();  // hide it
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
 <td>blabla</td>
 <td>Name: Messi</td>
 <td><a id="upload-button" href=".."/>button</a></td>
 <td>blabla</td>
</tr>
<tr>
 <td>blabla</td>
 <td>upload id: 123456</td>
 <td><a id="upload-button" href=".."/>button</a></td>
 <td>blabla</td>
</tr>
<tr>
 <td>blabla</td>
 <td>upload id: 654321</td>
 <td><a id="upload-button" href=".."/>button</a></td>
 <td>blabla</td>
</tr>
</table>

Be careful: id's should be unique.

Upvotes: 2

Related Questions