【问题标题】:How do you remove a element by id? [duplicate]如何通过 id 删除元素? [复制]
【发布时间】:2020-07-30 06:13:08
【问题描述】:

您好,我正在尝试让几个按钮工作,但我发现的所有其他东西在这里都不起作用

document.getElementById("Element").remove();

不工作

<button class="btn btn-danger" onclick="reset()">Reset</button>

错误:

script.js:30 Uncaught TypeError: Cannot read property 'remove' of null
at reset (script.js:30)
at HTMLButtonElement.onclick (index.html:14)

如果这格式很奇怪,我很抱歉,但我是新手。

【问题讨论】:

  • 要移除的元素是否有id="Element"
  • 按钮没有任何ID。您需要为其提供正确的 id 才能将其删除。
  • 你能贴出id为Element元素的完整代码
  • 如果您需要移除 id 为“Element”的按钮,那么该按钮需要具有 id="Element" 属性,但给出的示例没有 id 属性。
  • 这能回答你的问题吗? How to remove an HTML element using Javascript?

标签: javascript html


【解决方案1】:

试试这个

<button id="reset-button" class="btn btn-danger" onclick="reset()">Reset</button>

您可以通过以下方式删除按钮

document.getElementById("reset-button").remove();

【讨论】:

    【解决方案2】:

    您要删除的元素需要有id="Element"

    例如,如果你想删除一个 div,它看起来像:

    <div id="Element"> Div to remove </div>
    

    然后你的脚本:

    function reset() {
      document.getElementById("Element").remove();
    }
    

    适用于按钮:

    <button class="btn btn-danger" onclick="reset()">Reset</button>
    

    【讨论】:

      【解决方案3】:

      我没有明白你想要做什么,我假设你正在尝试删除按钮。

      您试图通过元素 id 获取按钮,但按钮标签中没有 id 属性, 它应该如下所示

      document.getElementById("id_name").remove();
      
      <button id="id_name" class="btn btn-danger" onclick="reset()">Reset</button>
      

      【讨论】:

        【解决方案4】:

        只需为您的按钮提供与您在删除中提供的相同名称的 id 名称。

        document.getElementById("Element").remove();
        <button id="Element" class="btn btn-danger" onclick="reset()">Reset</button>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-12-06
          • 2020-06-18
          • 1970-01-01
          • 2011-10-24
          • 2012-06-20
          • 1970-01-01
          • 2017-12-19
          相关资源
          最近更新 更多