-2

I am trying to hide two rows, <tr><td>line 1</td></tr> and <tr><td>line 2</td></tr>, by wrapping them in a div with display:none set, but these rows are not hidden. Why?

<script type="text/javascript">
  function toggle() {
    var ele = document.getElementById("toggleText");
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
      ele.style.display = "none";
      text.innerHTML = "Show";
    } else {
      ele.style.display = "block";
      text.innerHTML = "Hide";
    }
  } 
</script>

<table>
  <tr>
    <td>
      <a id="displayText" href="javascript:toggle();">Show</a>
    </td>
  </tr>

  <div id="toggleText" style="display: none;">
    <tr><td>line 1</td></tr>
    <tr><td>line 2</td></tr>
  </div>
</table>
Giang Nguyen
  • 495
  • 8
  • 22
  • Can we see your actual code please ? – Ryan Beaulieu Feb 04 '13 at 15:03
  • 1
    Show us what have you tried so far. – Renato Lochetti Feb 04 '13 at 15:04
  • if you're going to use a script tag you should either use the `type` attribute for files that are not `HTML5` or optionally no tag for files that are `HTML5`. Both will work but `type="text/javascript"` adheres to the latest standards for non `HTML5` pages. See this [reference](http://stackoverflow.com/questions/2267476/html-script-tag-type-or-language)... – War10ck Feb 04 '13 at 15:25
  • @War10ck - That comment would have been better phrased as an edit ... – Jonas Schubert Erlandsson Feb 04 '13 at 21:33
  • @d-Pixie I'm not sure I follow you. I shouldn't be editing something like that in the op's question. That would change the context of the original question. It's up to the op to make that change if and when he/she feels it is appropriate. It was merely a suggestion. – War10ck Feb 04 '13 at 21:51

2 Answers2

3

Your HTML markup is invalid, You can not have a div as a child element in a table!

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

When you want to put a div inside of a table it needs to live inside of a table cell, meaning inside of a td. Notice I am selecting the two divs by class name since id is intended to be unique.

<script language="javascript"> 
 function toggle() {
    var ele = document.getElementsByClassName("toggleText");
    var text = document.getElementById("displayText");
    if(ele[0].style.display == "block") {
        ele[0].style.display = "none";
        ele[1].style.display = "none";
        text.innerHTML = "Show";
    }
    else {
        ele[0].style.display = "block";
        ele[1].style.display = "block";
        text.innerHTML = "Hide";
    }
} 
</script>
<table>

    <tr><td>
    <a id="displayText" href="javascript:toggle();">Show</a>
    </td></tr>

    <tr><td><div class="toggleText">line 1</div></td></tr>
    <tr><td><div class="toggleText">line 2</div></td></tr>

</table>
DangerDan
  • 519
  • 2
  • 13