JQuery select multiple: nth-child ()

This is my table, use tr and td.

NAME Address CITY STATE ABC 123 A CA AB8 123 B CA AFC 456 B TX POI 985 C KJ 

After the document is ready, it will already hide everything.

Now I want the row to display all tr: -> Column (4) = CA "and" Column (3) = B

I am tired of my code:

 $("table[id=maintablex] tr td:nth-child(4):contains('CA'), table[id=maintablex] tr td:nth-child(3):contains('B')").closest('tr').show(); 

But it shows that everyone has (4) = CA, and (3) = B ... My code was "OR", can anyone help me with this?

Added FULL HTML CODE:

 <table id="table"> <tr> <td>ABC</td> <td>123</td> <td>A</td> <td>CA</td> </tr> <tr> <td>ABC</td> <td>1234</td> <td>B</td> <td>CA</td> </tr> <tr> <td>AUF</td> <td>123</td> <td>C</td> <td>TX</td> </tr> <tr> <td>ABC</td> <td>456</td> <td>B</td> <td>TX</td> </tr> </table> <script language="Javascript"> $("table[id=table] tr").hide(); // Code show here </script> 

The result I want to show is only:

 AB8 123 B CA 
+4
source share
4 answers

Why not do it like this:

 $("table[id=maintablex] tr td:nth-child(3):contains('B')", $("table[id=maintablex] tr td:nth-child(4):contains('CA')") ).closest('tr').show(); 

I don't know if this is faster, but based on @Jasper's answer, why not do this:

 //select the table, find all `<td>` elements that contain `CA` and iterate through each of them $('#table') .find('td:nth-child(4):contains("CA")') .closest('tr') .find('td:nth-child(3):contains("B")') .closest('tr') .addClass('active'); 

Here's jsfiddle: http://jsfiddle.net/KQMXe/

+1
source

Your very first selector will always match the lines where State = CA AND, where State = B. I would break it into two parts. Did not check this code, but it should close you ...

 var stateRows = ("#maintablex tr td:nth-child(4):contains('CA')").parent(); var matchRows = stateRows.find("td:nth-child(3):contains('B')").parent(); matchRows.doWhateverYouLikeWithTheResults(); 
+1
source

JS -

 //select the table, find all `<td>` elements that contain `CA` and iterate through each of them $('#maintablex').find('td:nth-child(4):contains("CA")').each(function (index, value) { //un-hide the parent `<tr>` element of this `<td>` by adding the `active` class to the `<tr>` $(this).parents('tr:first').addClass('active'); }); 

CSS -

 /*Hide all the table rows by default*/ tr { display : none; } /*declare a class that shows the table rows when added to them*/ tr.active { display : table-row; } 

UPDATE

I updated the code above to only look for the third column in each row (I have not used this part of the answer before).

Here's jsfiddle: http://jsfiddle.net/jasper/Mp7Jq/3/

0
source

try it

 $.each($('table#table tr td:nth-child(4):contains("CA")').parent(),function(){ if(($.inArray(this, $('table#table tr td:nth-child(3):contains("B")').parent())) > -1){ $(this).show(); } }); 

Hope this helps. :)

0
source

Source: https://habr.com/ru/post/1384007/


All Articles