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
  • 43,322
  • 6
  • 62
  • 109
user1612226
  • 19
  • 1
  • 5

4 Answers4

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
  • 160,666
  • 24
  • 190
  • 242
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
  • 38,217
  • 14
  • 107
  • 106
0

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,470
  • 10
  • 58
  • 82
0

Check Node.removeChild

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