Observing a dynamic HTML table with MutationsObserver

661 views Asked by At

I can't solve one question with MutationObserver.

Website has a table:

<table class='our_table'>
 <tbody>
  <tr>
      <td><span class='size'> S </span></td>

      <td><span class='price'>
        <em> /* first <em> in that <span> */
         450.00
        </em>
       </span>
      </td>

      <td>
       <span class='instock'>
        <em> /* first <em> in that <span> */
         25
        </em>
       </span>
      </td>

   </tr>
    ... here begins next <tr> with 3 tags <td> inside
    ... then more. Can be from 1 to 50 rows, there are 3 <td> in each row.

Table looks like.. S 450 25 M 330 60 L 530 30 ...

The code is:

var observer = new MutationObserver(function(mutations)
{
    // look through all mutations that have just occurred 
    for (var i = 0; i < mutations.length; i++) 
    {
        // look through all added nodes of this mutation
        for (var j = 0; j < mutations[i].addedNodes.length; j++)
        {
            var node = mutations[i].addedNodes[j];

            // look through each of 3 <td>'s:
            for (var p = 0; p < node.length; p++)
            {
                console.log('record № ' + p + ', text: ' + node.wholeText )
            };
        }
    }
});

observer.observe(document,
{
    attributes: false,          childList: true, 
    characterData: false,       subtree: true,
    attributeOldValue: false,   attributeFilter: false,
    characterDataOldValue: false
});

After the table content is changed, the script result is:

<td>№ 0, text: 450.00     // it's a **price**. But should be size, '**S**'
<td>№ 1, text: 450.00     // it's a **price**. All's right.
<td>№ 2, text: 450.00     // it's **price** again. But should be instock, 25 (pcs).

<td>№ 0, text: 550.00     // next <tr> of table is same..
<td>№ 1, text: 550.00
<td>№ 2, text: 550.00
....

Should be:

<td>№ 0, text: S  // size
<td>№ 1, text: 690.00 // price
<td>№ 2, text: 35 // in stock
...
0

There are 0 answers