0

I have a HTML table with following structure

<thead>
                        <tr>
                            <th>COMPANY</th>
                            <th>DATE</th>
                            <th>SHARE</th>
                            <th>COST PRICE</th>                                 
                        </tr>                
</thead>

In the data section I have following structure.

<tr>
                            <td rowspan="2">COMPANY1</td>
                            <td>DATE1</td>
                            <td>SHARE1</td>
                            <td>COST PRICE1</td>                                 
</tr> 

when I try to update the <td>s in the table dynamically from jquery I need to add some logic to check if first element has spanned multiple rows. I wanted to ask if we can update row based on the header, something like associative array.

Like this pseudo code $(this).td[<WHERE th=SHARE>].text("something)

rockfight
  • 1,916
  • 2
  • 20
  • 31
  • 1
    Why don't you assign class name to ``s when generating html? – Chaska Aug 14 '18 at 07:00
  • Seems like a good solution. In that case I also to add class to first element and check weather this class is null from the second element if first element spans multiple rows. How do I check if an element with particular class doesn't exists ? – rockfight Aug 14 '18 at 07:13
  • Never mind I didn't needed to find that. If you answer this question I can mark it as correct answer – rockfight Aug 14 '18 at 07:24

1 Answers1

1

I suggest that you should assign <td>s a class name when preparing the html mark up like this:

<tr>
  <td class="company" rowspan="2">COMPANY1</td>
  <td class="date">DATE1</td>
  <td class="share">SHARE1</td>
  <td class="cost-price">COST PRICE1</td>                                 
</tr>
<tr>
  <td class="date">DATE1</td>
  <td class="share">SHARE1</td>
  <td class="cost-price">COST PRICE1</td>                                 
</tr>

Javascript will be like this:

$('tr').each(function() {
  $(this).children('td.share').text('Share...');
  $(this).children('td.cost-price').text('Cost Price...');
});
Chaska
  • 3,165
  • 1
  • 11
  • 17
  • Thank you @Chaska, I used class and the solution was very elegant. But I used `$(this).find('td.share')` instead of `children`. Which will be better in your opinion. – rockfight Aug 15 '18 at 05:48
  • I think `find()` method is faster than `children()` in your case. Anyway please read this question for more details: https://stackoverflow.com/questions/648004/what-is-fastest-children-or-find-in-jquery – Chaska Aug 15 '18 at 05:58