0

I'm trying to remove an element that I created dynamically. This is how I created it...

var divTag = document.createElement("div");
divTag.id = "affiliation";
divTag.innerHTML = "Stuff Here";

I've tried several methods of removing it without success. Here's what I have so far.

var A = document.getElementById('affiliation');
A.parentNode.removeChild(A);

Suggestions?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user1612226
  • 19
  • 1
  • 5

4 Answers4

1

This snippet just works for me fine. The only difference is I added the "affiliation" divTag to the body

function insert() {
    var divTag = document.createElement("div");
    divTag.id = "affiliation";
    divTag.innerHTML = "Stuff Here";
    document.body.appendChild(divTag);
}
function remove() {
    var A = document.getElementById('affiliation');
    A.parentNode.removeChild(A);
}
Vikdor
  • 23,934
  • 10
  • 61
  • 84
0

If you wish to use jQuery, it is very easy to remove:

$("#affiliation").remove();

For the normal JavaScript, you can use this:

var node = document.getElementById("affiliation");
if (node.parentNode) {
    node.parentNode.removeChild(node);
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Did you appended to the body or a parent?

var divTag = document.createElement("div");
divTag.id = "affiliation";
divTag.innerHTML = "Stuff Here";
document.body.appendChild(divTag);


element = document.getElementById("affiliation");
element.parentNode.removeChild(element);​
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
0

Check Node.removeChild

var A = document.getElementById("affiliation");
if (A.parentNode) {
    A.parentNode.removeChild(A);
}
kushalbhaktajoshi
  • 4,640
  • 3
  • 22
  • 37