如何使用 Javascript 删除 HTML 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5933157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:34:37  来源:igfitidea点击:

How to remove an HTML element using Javascript?

javascripthtml

提问by Newbie Coder

I am a total newbie. Can somebody tell me how to remove an HTML element using the original Javascript not jQuery.

我是一个完全的新手。有人可以告诉我如何使用原始 Javascript 而不是 jQuery 删除 HTML 元素。

index.html

index.html

<html>
<head>
 <script type="text/javascript" src="myscripts.js" > </script>
 <style>
 #dummy {
  min-width: 200px;
  min-height: 200px;
  max-width: 200px;
  max-height: 200px;
  background-color: #fff000;
 }
 </style>
</head>
<body>
 <div id="dummy"></div>

 <form>
  <input type="submit" value="Remove DUMMY" onclick="removeDummy(); "/>
 </form>
</body>

myscripts.js

myscripts.js

function removeDummy() {
 var elem = document.getElementById('dummy');
 elem.parentNode.removeChild(elem);
}

What happens when I click the submit button, is that it will disappear for a very very short time and then appear back immediately. I want to completely remove the element when I click the button.

当我单击提交按钮时会发生什么,它会消失很短的时间,然后立即出现。我想在单击按钮时完全删除该元素。

回答by T.J. Crowder

What's happening is that the form is getting submitted, and so the page is being refreshed (with its original content). You're handling the clickevent on a submit button.

发生的事情是表单正在提交,因此页面正在刷新(使用其原始内容)。您正在处理click提交按钮上的事件。

If you want to remove the element and notsubmit the form, handle the submitevent on the form instead, and return falsefrom your handler:

如果要删除元素而不提交表单,请submit改为处理表单上的事件,然后false从处理程序返回:

HTML:

HTML:

<form  onsubmit="return removeDummy(); ">
    <input type="submit" value="Remove DUMMY"/>
</form>

JavaScript:

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}

But you don't need (or want) a form for that at all, not if its sole purpose is to remove the dummy div. Instead:

但是你根本不需要(或想要)一个表单,如果它的唯一目的是删除虚拟 div。反而:

HTML:

HTML:

<input type="button" value="Remove DUMMY" onclick="removeDummy()" />

JavaScript:

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}


However, that style of setting up event handlers is old-fashioned. You seem to have good instincts in that your JavaScript code is in its own file and such. The next step is to take it further and avoid using onXYZattributes for hooking up event handlers. Instead, in your JavaScript, you can hook them up with the newer (circa year 2000) way instead:

然而,这种设置事件处理程序的风格已经过时了。你似乎有很好的直觉,因为你的 JavaScript 代码在它自己的文件中等等。下一步是更进一步,避免使用onXYZ属性来连接事件处理程序。相反,在您的 JavaScript 中,您可以使用更新的(大约 2000 年)方式将它们连接起来:

HTML:

HTML:

<input id='btnRemoveDummy' type="button" value="Remove DUMMY"/>

JavaScript:

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}
function pageInit() {
    // Hook up the "remove dummy" button
    var btn = document.getElementById('btnRemoveDummy');
    if (btn.addEventListener) {
        // DOM2 standard
        btn.addEventListener('click', removeDummy, false);
    }
    else if (btn.attachEvent) {
        // IE (IE9 finally supports the above, though)
        btn.attachEvent('onclick', removeDummy);
    }
    else {
        // Really old or non-standard browser, try DOM0
        btn.onclick = removeDummy;
    }
}

...then call pageInit();from a scripttag at the very end of your page body(just before the closing </body>tag), or from within the windowloadevent, though that happens very latein the page load cycle and so usually isn't good for hooking up event handlers (it happens afterall images have finally loaded, for instance).

...然后pageInit();script页面末尾的标签body(就在结束</body>标签之前)或从windowload事件内部调用,尽管这发生在页面加载周期的后期,因此通常不适合连接事件处理程序(例如,它所有图像最终加载发生)。

Note that I've had to put in some handling to deal with browser differences. You'll probably want a function for hooking up events so you don't have to repeat that logic every time. Or consider using a library like jQuery, Prototype, YUI, Closure, or any of several othersto smooth over those browser differences for you. It's very importantto understand the underlying stuff going on, both in terms of JavaScript fundamentals and DOM fundamentals, but libraries deal with a lot of inconsistencies, and also provide a lot of handy utilities — like a means of hooking up event handlers that deals with browser differences. Most of them also provide a way to set up a function (like pageInit) to run as soon as the DOM is ready to be manipulated, long before windowloadfires.

请注意,我不得不进行一些处理来处理浏览器差异。您可能需要一个用于连接事件的函数,这样您就不必每次都重复该逻辑。或者考虑使用像jQueryPrototypeYUIClosure其他几个库这样的库来为您消除这些浏览器差异。这是非常重要的了解底层的东西怎么回事,两者在JavaScript的基本面和DOM基本面方面,但库处理很多不一致的,同时还提供了很多方便的工具-像挂钩事件处理程序的手段涉及浏览器差异。它们中的大多数还提供了一种设置函数的方法(例如pageInit) 在 DOM 准备好被操纵时立即运行,早在windowload触发之前。

回答by Muhammad Umer

Just do this element.remove();

就这样做 element.remove();

Try it here LOOK

在这里试试看

http://jsfiddle.net/4WGRP/

http://jsfiddle.net/4WGRP/

回答by CoderHawk

You should use input type="button" instead of input type="submit".

您应该使用 input type="button" 而不是 input type="submit"。

<form>
  <input type="button" value="Remove DUMMY" onclick="removeDummy(); "/>
 </form>

Checkout Mozilla Developer Centerfor basic html and javascript resources

查看Mozilla 开发人员中心以获得基本的 html 和 javascript 资源

回答by Pav

Your JavaScript is correct. Your button has type="submit"which is causing the page to refresh.

你的 JavaScript 是正确的。您的按钮具有type="submit"导致页面刷新的功能。

回答by mVChr

It reappears because your submit button reloads the page. The simplest way to prevent this behavior is to add a return falseto the onclicklike so:

它重新出现是因为您的提交按钮重新加载了页面。为防止这种行为的最简单的方法是将添加return falseonclick像这样:

<input type="submit" value="Remove DUMMY" onclick="removeDummy(); return false;" />

回答by Newtang

Change the input type to "button". As T.J. and Pav said, the form is getting submitted. Your Javascript looks correct, and I commend you for trying it out the non-JQuery way :)

将输入类型更改为“按钮”。正如 TJ 和 Pav 所说,表单正在提交。你的 Javascript 看起来是正确的,我赞扬你尝试非 JQuery 的方式:)

回答by alex

That is the right code. What is probably happening is your form is submitting, and you see the new page (where the element will exist again).

那是正确的代码。可能发生的情况是您的表单正在提交,并且您看到新页面(元素将再次存在的页面)。

回答by e-motiv

index.html

索引.html

<input id="suby" type="submit" value="Remove DUMMY"/>

myscripts.js

我的脚本.js

document.addEventListener("DOMContentLoaded", {
//Do this AFTER elements are loaded

    document.getElementById("suby").addEventListener("click", e => {
        document.getElementById("dummy").remove()
    })

})

回答by Sim Reaper

Try running this code in your script.

尝试在您的脚本中运行此代码。

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

And it will hopefully remove the element/button.

它有望删除元素/按钮。

回答by Durtle02

This works. Just remove the button from the "dummy" divif you want to keep the button.

这有效。div如果您想保留按钮,只需从“虚拟”中删除按钮即可。

function removeDummy() {
  var elem = document.getElementById('dummy');
  elem.parentNode.removeChild(elem);
  return false;
}
#dummy {
  min-width: 200px;
  min-height: 200px;
  max-width: 200px;
  max-height: 200px;
  background-color: #fff000;
}
<div id="dummy">
  <button onclick="removeDummy()">Remove</button>
</div>