根据包含的td属性隐藏表行

时间:2014-06-04 06:44:23

标签: javascript html css

<table border="1">
 <tr>
  <td>
   <div class="xyz">Division 1</div>
  </td>
 </tr>
 <tr>
  <td>
   <div class="abc">Division 2</div>
  </td>
 </tr>
</table>

请注意<td>内容是动态添加的。我需要根据其<tr><td>隐藏第二个<div>。请在css / javascript方法中建议并且没有jQuery因为html不支持jQuery

由于

3 个答案:

答案 0 :(得分:0)

试试这个

var div = document.getElementsByTagName("div");
for (var i = 0; i<div.length; i++) {
  if (div[i].className == "abc") {
  div[i].style.visibility="hidden";
  }
}

小提琴:http://jsfiddle.net/4QNBs/

修改

隐藏父tr

var div = document.getElementsByTagName("div");
for (var i = 0; i<div.length; i++) {
  if (div[i].className == "abc") {
 // div[i].style.visibility="hidden";
      parenttd = div[i].parentNode;
      parenttr = parenttd.parentNode;
      parenttr.style.display="none";
  }
}

小提琴:http://jsfiddle.net/4QNBs/3/

答案 1 :(得分:0)

http://jsfiddle.net/6HQmP/1/

如果你想隐藏tr,你应该根据div给tr提供相关的id,这里我给div的名字命名为tr id

HTML:

<table>
 <tr id='xyz'>
   <td>
    <div class="xyz">Division 1</div>
   </td>
 </tr>
 <tr id='abc'>
   <td>
    <div class="abc">Division 2</div>
   </td>
 </tr>
</table>

CSS:

var div_ele = document.getElementsByTagName("div");
for (var i = 0; i<div_ele.length; i++) {
  if (div_ele[i].className == "abc") {
     // document.getElementById("abc").style.display="none";
     div_ele[i].parentNode.parentNode.style.display="none";

  }
}

如果你不能给tr一个相对的id,你可以试试这个:

div_ele[i].parentNode.parentNode.style.display="none";

http://jsfiddle.net/6HQmP/2/

答案 2 :(得分:0)

JSFiddle:http://jsfiddle.net/Cheejyg/uaMxd/1/

HTML:

<table border="1">
    <tr>
        <td>
            <div class="xyz">Division 1</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="abc">Division 2</div>
        </td>
    </tr>
</table>


JS:

var tr = document.getElementsByTagName('tr');

for(var i = 0; i < tr.length; i++) {
    switch(tr.item(i).getElementsByTagName('div').item(0).className) {
        case "abc":
        case "other div class names":
            tr.item(i).style.display = "none";
            break;
    }
}