Javascript get access to inner table only

时间:2019-03-19 14:48:44

标签: javascript html dom

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.

2 个答案:

答案 0 :(得分:4)

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>

答案 1 :(得分:1)

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>