user2865400
user2865400

Reputation: 149

Need help removing entire div "onClick" using JavaScript

I am trying to delete the div when I click on it, yet I am unsure of how to go about this. Any help would be greatly appreciated.

HTML

<div onclick="fadeOut(this)"></div>

JavaScript

function fadeOut(i) {
    ????
}

Upvotes: 0

Views: 86

Answers (4)

Amar Kate
Amar Kate

Reputation: 71

Using jquery you can do it as follow.

Script:

function deletediv(id) {
    $("#" + id).remove();
}

html:

 <div id="testdiv" style="background-color:Red; height:100px; width:100px;" onclick="deletediv(this.id)"></div> 

Upvotes: 0

Shailesh Saxena
Shailesh Saxena

Reputation: 3502

Even you can directly do this:(If this is specific to current div.)

<div onclick="this.parentNode.removeChild(this);">xyz</div>

Upvotes: 0

Jay Harris
Jay Harris

Reputation: 4271

You can use outerHTML its the inverse of innerHTML as in outerHTML pertains to only the element.

function fadeOut(i) {
  i.outerHTML = ''; // deletes it from the DOM
}

And if you don't want to display it but keep it in the DOM

function fadeOut(i) {
  i.style.display = 'none'; // hides the element
}

JSFIDDLE

Upvotes: 0

Robin
Robin

Reputation: 7895

Use:

function fadeOut(i) {
    i.parentElement.removeChild(i);
}

Upvotes: 3

Related Questions