0

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.

0

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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();

}

1 Comment

Ok, thanks. I edited $(IDObj) to IDObj since var IDObj = $('#TheTable... effectively returns a jquery object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.