Serkan Taşkın Serkan Taşkın - 4 months ago 10
HTML Question

Parsing HTML with Javascript / jQuery or PHP

<table>
<tbody>
<tr>
<td>
<span class="big">Fruits</span>
</td>
</tr>
<tr>
<td>
<span class="small">Apple</span>
</td>
</tr>
<tr>
<td>
<span class="small">Apricot</span>
</td>
</tr>
<tr>
<td>
<span class="small">Carrot</span>
</td>
</tr>
<tr>
<td>
<span class="big">Colors</span>
</td>
<tr>
<td>
<span class="small">Red</span>
</td>
</tr>
<tr>
<td>
<span class="small">Blue</span>
</td>
</tr>
</tbody>
</table>


I have more than 10k tables like this, and need to parse them like

Fruits: Apple Apricot Carrot
Colors: Red Blue


Categories have different class names and objects have different class names, but they are all in the same table.

Answer

Here's my implementation:

var items = {};
var lastItem = null;

$('.big, .small').each(function() {
  var content = $(this).text();
  var cls = $(this).attr('class');

  if ( cls == 'big' )
  {
    lastItem = content;
    items[lastItem] = [];
    return;
  }

  items[lastItem].push(content);
});

console.log(items);

var items = {};
var lastItem = null;

$('.big, .small').each(function() {
  var content = $(this).text();
  var cls = $(this).attr('class');
  
  if ( cls == 'big' )
  {
    lastItem = content;
    items[lastItem] = [];
    return;
  }
  
  items[lastItem].push(content);
});

console.log(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
 <tbody>
  <tr>
   <td>
    <span class="big">Fruits</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Apple</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Apricot</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Carrot</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="big">Colors</span>
   </td>
  <tr>
   <td>
    <span class="small">Red</span>
   </td>
  </tr>
  <tr>
   <td>
    <span class="small">Blue</span>
   </td>
  </tr>
 </tbody>
</table>