FoxyBOA
FoxyBOA

Reputation: 5846

Javascript get access to inner table only

I have a system that generates a list of nested tables. I can't either modify it nor add any id/tags/classes to any parent tables. I also can add neither jQuery nor any other JS library.

I wish to add highlights on mouseover on a row of the inner table (usually I have 2-3 nested tables).

Could someone help me to adjust that sample to my case? The problem with the code that it grabs <td/> tags of parent tables.

var tds = document.getElementsByTagName( "td" );
    for( var i = 0; i < tds.length; i++ ) {
      tds[i].addEventListener("mouseover", function(){
          var children = this.parentNode.getElementsByTagName("td");
          for( var j = 0; j < children.length; j++ )
            children[j].style.backgroundColor = "green";
          });
      tds[i].addEventListener("mouseout", function(){
         var children = this.parentNode.getElementsByTagName("td");
            for( var j = 0; j < children.length; j++ )
                    children[j].style.backgroundColor = "initial";
            });
        }
    
   

<table>
    <tr>
    <td>
        <table>
            <tr>
                <td>cell1,1</td>
                <td>cell1,2</td>
                <td>cell1,3</td>
            </tr>
            <tr>
                <td>cell2,1</td>
                <td>cell2,2</td>
                <td>cell2,3</td>
            </tr>
        </table>
    </td>
    <td> test </td>
    </tr>
</table>

Unfortunately, I'm not good enough in JS yet.

Upvotes: 0

Views: 337

Answers (2)

Ehtesham Z
Ehtesham Z

Reputation: 102

The answer mentioned above works if the number of nested tables are always 2. According to the requirements, you mentioned that you usually have 2-3 nested tables so it wouldn't work if there are 3 nested tables or more. You would have to change your CSS selectors.

With the solution below, it makes it more dynamic to always get the row of the inner most table as originally requested.

var tables = document.getElementsByTagName("table");
tables[tables.length - 1].classList.add("highlighter");
.highlighter tr:hover {
  background: green;
}
<table>
  <tr>
    <td>
      <table>
        <tr>
          <td>cell1,1</td>
          <td>cell1,2</td>
          <td>cell1,3</td>
        </tr>
        <tr>
          <td>cell2,1</td>
          <td>cell2,2</td>
          <td>cell2,3</td>
        </tr>
      </table>
    </td>
    <td> test </td>
  </tr>
</table>

Upvotes: 1

j08691
j08691

Reputation: 207953

I'd ditch the JavaScript and use a simple CSS selector

table table tr:hover {
  background: green;
}
<table>
  <tr>
    <td>
      <table>
        <tr>
          <td>cell1,1</td>
          <td>cell1,2</td>
          <td>cell1,3</td>
        </tr>
        <tr>
          <td>cell2,1</td>
          <td>cell2,2</td>
          <td>cell2,3</td>
        </tr>
      </table>
    </td>
    <td> test </td>
  </tr>
</table>

Upvotes: 4

Related Questions