使用JavaScript删除td

时间:2018-09-07 09:21:03

标签: javascript

是否有一种方法可以从此表中删除td(请参阅注释中的td“要删除”),而无需编辑HTML。 另外,不仅要使用这些类,因为我在另一个表中具有相同的类,因此不需要删除它们,因此也要确定span ID。提前致谢!

       <div id="pnlPersonalDetails2">

                  </div><table cellpadding="0" cellspacing="0" border="0" class="surveyquestions">
              <tbody><tr>

                <td colspan="2" class="pd_question">
                    <span id="lbl2"></span>
                  </td>
                  </tr><tr>
                    <td class="pd_label">FIRST NAME<span class="red"> *</span></td>
                    <td>
                      <input name="Name微statictext_2" type="text" id="Name微statictext_2" class="pd_textbox">
                    </td>
                    <!-- To be removed
                    <td class="error_label">
                      <span id="ctl03" style="visibility:hidden;">Required Field</span>
                    </td>-->
                  </tr>

            </tbody></table>
    <div id="pnlPersonalDetails3">

          </div><table cellpadding="0" cellspacing="0" border="0" class="surveyquestions">
      <tbody><tr>
 <!-- To be removed      
  <td colspan="2" class="pd_question">
            <span id="lbl3"></span>
          </td>-->
      </tr><tr>
        <td class="pd_label">LAST NAME<span class="red"> *</span></td>
        <td>
          <input name="Name微statictext_3" type="text" id="Name微statictext_3" class="pd_textbox">
        </td>
        <td class="error_label">
          <span id="ctl04" style="visibility:hidden;">Required Field</span>
        </td>
      </tr>

这就是现在的样子

enter image description here

这是删除注释的td后的样子

enter image description here

我已经在https://codepen.io/duicug/pen/VGreQZ

中附加了整个代码

4 个答案:

答案 0 :(得分:0)

one_method

您可以参考此网站,很好的示例https://www.w3schools.com/jsref/prop_style_display.asp

希望可以为您提供帮助。

答案 1 :(得分:0)

<td class="error_label">
  <span id="ctl03" style="visibility:hidden;">Required Field</span>
</td>

<td colspan="2" class="pd_question">
  <span id="lbl3"></span>
</td>

<script>
  document.getElementById("ctl03").parentElement.remove();
  document.getElementById("lbl3").parentElement.remove();
</script>

答案 2 :(得分:-1)

您可以使用querySelector查找此类:

var target = document.querySelector("#pnlPersonalDetails2 .error_label");

有多种方法可以将其从DOM中删除。

您可以将其保留在内存中,以便以后可以轻松地再次显示:

target.style.display = "none";  //Undo by setting to "" or to previous value

或者您可以使其不可见,从而将其保留在内存中并更改周围内容的布局:

target.style.visibility = "hidden";  //Undo by setting to "" or to previous value

或者您可以将其从DOM中完全删除:

target.parent.removeChild(target);

答案 3 :(得分:-1)

尝试使用jQuery:

$("#lbl2").toggle();

也许这会对您有所帮助?    var el = document.getElementById('lbl2');     el.parentElement.hidden = true; 或删除td var el = document.getElementById('ctl03');     el.parentElement.remove();