简体   繁体   English

阻止创建特定的HTML元素

[英]Prevent specific HTML elements from being created

Imagine this: I know that an element with id="cats" will be created sometime, but I don't know when. 想象一下:我知道有时会创建一个id="cats"的元素,但是我不知道何时。

I can remove an element that already exists like this: 我可以删除这样一个已经存在的元素:

document.getElementById('cats').style.display = 'none';

But is there any way to block that element before it even exists , so it can never be created? 但是,有什么方法可以在该元素存在之前将其阻止,从而永远无法创建它? Or detect and delete it immediately after it has been created? 还是在创建后立即检测并删除它? (pure JavaScript answers have advantage) (纯JavaScript答案具有优势)

Important note: I can't edit CSS 重要说明:我无法编辑CSS

与其阻止创建的元素,不如不简单地将其隐藏在CSS中?

#cats { display:none }

If you want to have a javascript only solution, you could do two things: 如果您想使用纯JavaScript解决方案,则可以做两件事:

  1. Find a way to watch for DOM manipulations. 找到一种监视DOM操作的方法。 This is not easily be done cross browser. 跨浏览器不容易做到这一点。 There is a post about it here: Detect changes in the DOM 这里有一篇关于它的文章: 检测DOM中的更改

  2. Run an interval every seconds (or so) and check for the ID , then it can quickly be deleted, after it has been created. 每隔一秒钟(或如此) 运行一个间隔检查ID ,然后在创建ID之后即可将其快速删除。 Keep in mind, that this is a lot of overhead. 请记住,这是很多开销。

 (function() { window.setInterval(function() { var elem = document.getElementById('cats'); if (elem) { elem.parentNode.removeChild(elem); } }, 1000) }()); (function () { button = document.getElementById('creator'); button.addEventListener('click', function () { var element = document.createElement('div'); element.id = 'cats' document.body.appendChild(element); }) }()); 
 #cats { background: red; width: 100px; height: 100px; } 
 <button id="creator">Create Element</button> 

Usually you should be able to control who or what manipulates the DOM, and thus be able to avoid the creation in the first place. 通常,您应该能够控制由谁或什么来操纵DOM,因此首先可以避免创建。

Combine Hugos display: none;-solution with a check if the id is already in use (and if so, remove it from the DOM) when you are going to introduce your element with that id. 结合Hugos display:none;-解决方案,并在要引入具有该ID的元素时检查ID是否已在使用(如果已使用,请从DOM中将其删除)。 The css rule will not prevent the creation of an element with that id within your DOM, so there is still the chance that an element with this id could be created before you are getting to action. css规则不会阻止在DOM中创建具有该id的元素,因此仍然有可能在开始采取行动之前创建具有该id的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM