How to use jQuery.each () to search for child children?

Given the many TABLE tags on the page, how do I select a TD child group in the selected table.

This is logical, but an error with this error:

Error: uncaught exception: Syntax error, unrecognized expression: [object Object]tr 

My code

 $(document).ready(function () { var selectedTable = $('table').eq('9'); $(selectedTable).css('border','10px solid green'); $(selectedTable + 'tr td').each(function(i) { $(this).css('border','10px solid blue'); }); }); 
+6
source share
4 answers

selectedTable is a jQuery object, not a string.
You cannot use it in a selector.

Instead, you need to use the jQuery traversal API:

 selectedTable.find('tr td') 
+6
source
 $(selectedTable).find('td').each(function (index, element) { ... }); 
+23
source
 selectedTable.find('tr td').each(function(i) { $(this).css('border','10px solid blue'); }); 

You can also chain as shown below:

 selectedTable.css('border','10px solid green').find('tr td').each(function(i) { $(this).css('border','10px solid blue'); }); 

Also, you don't need to use $ (selectedTable) again, since your selector already returns a jquery object.

+3
source

Use .find() to get the children of the table. The problem you are facing is that selectedTable not an selector string, but an object. You cannot concatenate an object with a string, so you get your error.

This should work fine:

 $(document).ready(function () { var selectedTable = $('table').eq('9'); $(selectedTable).css('border','10px solid green'); $(selectedTable).find('tr td').each(function(i) { $(this).css('border','10px solid blue'); }); }); 
+3
source

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


All Articles