Test Account
Test Account

Reputation: 11

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.

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)

Important note: I can't edit CSS

Upvotes: 1

Views: 2608

Answers (3)

iquellis
iquellis

Reputation: 1053

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. 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.

Upvotes: 0

Rias
Rias

Reputation: 1996

If you want to have a javascript only solution, you could do two things:

  1. Find a way to watch for DOM manipulations. This is not easily be done cross browser. There is a post about it here: Detect changes in the 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. 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.

Upvotes: 0

Hugo W.
Hugo W.

Reputation: 84

Instead of blocking the element being created, why not simple hide it in your css?

#cats { display:none }

Upvotes: 5

Related Questions