Reputation: 169
I have the follow code:
var table1 = $('[id="table1"]');
var table2 = $('[id="table2"]');
I need to get inside each table the text content from specified id as this:
var words1 = $('[id^="table-row-"]');
var words2 = $('[id^="table-row-"]');
Please note that id^="table-row-"
because it is variable as for example "table-row-1", "table-row-2", etc.
I tried something like this but it does not works:
var words1 = $('[id^="table-row-"]').table1;
What I need to do?
Upvotes: 0
Views: 65
Reputation: 3038
Why not use the native (non-jQuery) querySelector?
var table = document.querySelector("table");
var row = table.querySelector("tr");
var cell = row.querySelector("td");
alert(cell.innerHTML);
...or, if you insist on using jQuery:
var $tables = $("table");
var $rows = $($tables[0]).find("tr");
var $cells = $($rows[0]).find("td");
alert($($cells[0]).html());
That's slightly different because jQuery returns all elements (in the above example, using $(xxx[0]) to get the first instance). If you want to find all instances the native way, use querySelectorAll.
Upvotes: 0
Reputation:
For all rows:
var words1 = $('[id="table1"] [id^="table-row-"]');
var words2 = $('[id="table2"] [id^="table-row-"]');
For one row:
var words1 = $('[id="table1"] [id="table-row-' + id + '"]');
var words2 = $('[id="table2"] [id="table-row-' + id + '"]');
Upvotes: 0
Reputation: 1804
First, you can use the #
to find IDs:
var $table1 = $('#table-1');
You can space separate child selectors like so:
var $table1row1 = $('#table-1 #table-row-1');
Or, if you have your initial jQuery object cached, you can perform a $.find()
:
var $table1 = $('#table-1'),
$tableRow1 = $table.find('#table-row-1');
However, IDs should always be unique to the entire document. Never use the same ID on more than one element. If you have an ID called table-row-1
, that should be the only time that ID appears in the document, and you can simply do:
var $tableRow1 = $('#table-row-1');
I believe your HTML should probably look more like this:
<table id="table-1">
<tr class="table-row-1">
<td></td>
</tr>
<tr class="table-row-2">
<td></td>
</tr>
</table>
<table id="table-2">
<tr class="table-row-1">
<td></td>
</tr>
<tr class="table-row-2">
<td></td>
</tr>
</table>
So you have classes that are reusable across multiple tables, and then you can do finds for the table rows in each table.
$table1row1 = $('#table-1 .table-row-1');
Also note that if you're just incrementing the rows, you can also find elements by their index within the parent element. So, given the above HTML:
$('#table-one tr').eq(1); // returns the first tr element in #table-one
Note: it's customary when storing jQuery objects to preface the variable name with a $
to connote that it's a referencing a jQuery object.
Upvotes: 1
Reputation: 2300
you can access by there index
$('[id^="table-row-"]')[0]
$('[id^="table-row-"]')[1]
Upvotes: 0