Search code examples
javascriptarrayschild-nodes

Initializing a variable with childNodes out of an array


Can someone help explain what the following JavaScript syntax was meant to do:

  var tagLink_ar = document.getElementsByTagName('td');  

  **var x = tagLink_ar.childNodes, i=0, j;**                 // Not sure ???

This is from an older javascript function that no longer works in IE>9 or FF.

tagLink_ar of course is the array of TD tags, yet I have not previously seen a variable with an index element i and j, and can't find a similar descriptor in my research online. Does i just reference the starting element and j the length?

Thoughts on how to load x in a similar manner?


Makes sense it is a simple declaration for x, i and j. Yet getting a "TypeError: x is undefined".

Below is the function as a reference:

var tagLink_ar = document.getElementsByTagName('td');  
**var x = tagLink_ar.childNodes, i=0, j;**                 // Not sure ???

while(j == x[i++]){                                             
  if(j.nodeType == 1 && nodeName == 'div'){                     
     var viewDiv = getStyle(divElement, 'display');
     if (viewDiv == 'block'){                                   
       x[j].style.borderBottom = "1px solid #000000";
     }
   }
}

Noted the syntax error on the while, should have been j=x[i++], and j.nodeName


Solution

  • There is no reasonable circumstance where x could have a childNodes property. tagLink_ar is a NodeList, and each of the elements in that list has a childNodes property.

    There are a few other reasons why that code would never work. Did you copy it correctly?

    To get the result the code was designed to have, you can do this (I'm including some sample HTML so that you can run it as a snippet):

    var tagLink_ar = document.getElementsByTagName('td'),
        children, i, j, node, viewDiv;
    
    for (i = 0; i < tagLink_ar.length; i += 1) {
        children = tagLink_ar[i].childNodes;
        for (j = 0; j < children.length; j += 1) {
            node = children[j];
    
            if (node.nodeType === 1 && 
                node.nodeName.toLowerCase() === 'div' && 
                node.style.display === 'block') {
                
                node.style.borderBottom = "1px solid #000000";
            }
        }
    }
    <table>
        <tr>
            <td>
                <div>a</div>
            </td>
            <td>
                <div style="display: block;">b</div>
            </td>
        </tr>
        <tr>
            <td>
                <div style="display: block;">c</div>
            </td>
            <td>
                <div style="display: block;">b</div>
            </td>
        </tr>
        <tr>
            <td>
                <div>e</div>
            </td>
            <td>
                <div>f</div>
            </td>
        </tr>
    </table>