NineSix
NineSix

Reputation: 25

Removing HTML from DOM

I have to use Google Tag Manager to make a change to fix something temporarily until I gain access to the back-end of a site. I am trying to remove a div container based on class. I have been able to successfully create a custom HTML tag with the following code to add remove the div container like so:

<script> 
function changeHtml () 
{ 
document.getElementsByClassName("signup")[0].style.display = "none"; 
} 
change = changeHtml(); 
</script>

The issue is that the problematic item in this div container is a form. I quickly found out that if you apply display: none; via css the form still works. The true way to remove this would be to remove it from the DOM. I tried adding the following JS but not having any success:

<script>
const elem = document.getElementsByClassName('signup');
elem.parentNode.removeChild(elem);
</script>

Receiving error:

Javascript Compiler error: Error at line 3, character 1: This language feature is only supported for ECMASCRIPT6 mode of better: const declaration

Upvotes: 0

Views: 339

Answers (3)

Eike Pierstorff
Eike Pierstorff

Reputation: 32780

As of now, GTM supports ES6 only in custom templates, so the use of const in a custom javascript tag will result in an error. Your description is somewhat generic ("does not work"), so will just assume that this is your problem. Also your tag must be executed only after the element you want to remove actually exists (on DOM ready, or with a visibility trigger).

Upvotes: 0

KienHT
KienHT

Reputation: 1346

Use remove() method to remove the selected element from the DOM:

<script>
  document.getElementsByClassName('signup')[0].remove();
</script>

Upvotes: 1

Elijah Enuem-Udogu
Elijah Enuem-Udogu

Reputation: 296

You could achieve this easily by trying this instead

<script>
  const elem = document.getElementsByClassName('signup')[0];
  elem.outerHTML = '';
</script>

Upvotes: 0

Related Questions