Reputation: 52027
Let's say I have some html that looks like this:
<div id="TheTable">
<div class="TheRow">
<div class="TheID">123</div>
<div class="TheQuantity">2</div>
<div class="TheName">test1</div>
</div>
<div class="TheRow">
<div class="TheID">456</div>
<div class="TheQuantity">3</div>
<div class="TheName">test2</div>
</div>
</div>
And let's say I have 1,000 rows.
I'm writing a function that takes in an ID as parameter and that searches for the TheQuantity and TheName values in the html. Something like this:
function GetData(TheID) {
var TheIndex = $('#TheTable').find("the index of the row that contains TheID")
TheQuantity = $('#TheTable .TheQuantity').eq(TheIndex);
TheName = $('#TheTable .TheName').eq(TheIndex);
}
I could loop through each .TheID and return the index like this:
$('#TheTable .TheRow').each( function () {
if ($(this).html() === TheID) { return $(this).index(); }
});
but I'm wondering if there's a more direct way of doing it. Let me know if you have some suggestions.
Thanks.
Upvotes: 0
Views: 7342
Reputation: 682
Following function will help to get the corresponding data:
function GetData(TheID) {
var IDObj = $('#TheTable .TheID').filter(function(){
return $.trim($(this).text()) == TheID;
})
TheQuantity = IDObj.siblings('.TheQuantity').text();
TheName = IDObj.siblings('.TheName').text();
}
Upvotes: 1
Reputation: 171690
If you have the ability to add additional attributes to the elements will help search efficiency. For example adding a data attribute
<div class="TheID" data-id="123">123</div>
var rowIndex= $('.TheID[data-id="'+TheID+'"]').parent().index();
For all values:
var row= $('.TheID[data-id="'+TheID+'"]').parent();
var name= row.find('.TheName').text();
var qty=row.find('.TheQuantity').text();
EDIT: Here's another way using filter method if unable to add attributes to markup:
var row= $('.TheID').filter(function(){
return $(this).text()==TheID;
}).parent();
var name= row.find('.TheName').text();
var qty=row.find('.TheQuantity').text();
Upvotes: 3