0

I'm trying to add a button with a link after a div that has no id, using Google Tag Manager. I'm taking the specific div (without id) using the code below, but when I try to put the button after that div using innerHTML, the div is replaced by the button, and if I use appendChild (commented in my code) nothing happens.

<script>
  var HTML = '<a href="#" target="_blank" class="button" >Send</a>'
  var title = document.getElementsByClassName("class_title");
  title[0].nextSibling.nextSibling.setAttribute("id", "newdiv");
  document.getElementById("newdiv").innerHTML = HTML;
  //getElementById("newscript").appendChild(HTML);
</script>

What am I doing wrong? Thanks a lot!

Eu Román
  • 165
  • 1
  • 1
  • 11

2 Answers2

1

Generally, to insert a node after another, you use this (taken from this answer):

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

To use insertBefore, you should create a link element using JavaScript, and then insert it, like so:

<script>
  var a = document.createElement('a');
  var linkText = document.createTextNode("Send");
  a.appendChild(linkText);
  a.target = "_blank";
  a.href = "#";
  a.class = "button";
  var referenceNode = document.getElementsByClassName("class_title")[0].nextSibling.nextSibling;
  referenceNode.parentNode.insertBefore(a, referenceNode.nextSibling);
</script>
d4nyll
  • 11,811
  • 6
  • 54
  • 68
  • 1
    This was exactly what I needed! With your help, I've been able to do it exactly how I wanted and now it works like a charm. I have to say that this is the only way it works for me. Thanks a lot, @d4nyll! – Eu Román Nov 07 '17 at 20:33
0

It's easy.

Your question is already answered here

In your case, do this:

// Create a variable for the element you want. Make it easy to read.
var element = document.getElementById("new_div");

element.parentNode.insertBefore(HTML, element.nextSibling);

Read the linked question to see the explanation in details.

Beto Silva
  • 58
  • 6