Farouk Tawtaw
Farouk Tawtaw

Reputation: 68

removing a div by an onclick event

I am trying to remove a div with an onclick event but it's not working and the div stays there, below is the code I am using, anyone can help?

<div id="apDiv2">
    <a href="#" onclick="document.getElementById('apDiv2').removeChild(document.getElementById('apDiv1'))">
        <div id="apDiv1"></div>
    </a>
</div>

Upvotes: 1

Views: 82

Answers (1)

ComFreek
ComFreek

Reputation: 29424

Try this:

<div id="apDiv2">

<a href="#" onclick="this.removeChild(this.firstChild)"><div id="apDiv1">T</div></a>

</div>
  • removeChild() only removes a direct child.

  • I also made the code a bit cleaner:

    • this references the event's tag itself (in this case the <a> tag)
    • this.firstChild points to the first child of the link tag: the <div id="apDiv1">

By the way, please take a look in the developer console of your browser (e.g. F12 in Chrome) the next time. You would have seen an eror which you could post here. It will help people helping you ;)


An even better way would be to put the JavaScript in its own file (or at least in a block) and to use the IDs for referencing the elements.

I'd give the link another ID, say for example myLink:

document.getElementById("myLink").addEventListener("click", function () {
  this.removeChild(this.firstChild);
});

In case you cannot specify an ID for the link tag, there are multiple ways for using the outer apDiv2 as a reference point, e.g.:

var linkTag = document.querySelector("#apDiv2 a");
// or
var linkTag = document.getElementById("apDiv2").getElementsByTagName("a")[0];

Upvotes: 3

Related Questions