a.m.
a.m.

Reputation: 2208

How can I remove an element in Javascript without jQuery

Im trying to remove a Div from the DOM via an <a> tag nested within it.

I guess what I am looking for is the pure Javascript version of jQuery's $('div').remove() Here's the html set up

<div> <a href = "#" onClick = "w/e()">Click me to remove the parent div</a></div>

Thanks ahead of time. :D

Upvotes: 14

Views: 12934

Answers (1)

Felix Kling
Felix Kling

Reputation: 817030

You could define this function

function remove(element) {
    element.parentNode.removeChild(element);
}

and use it as

<div>
    <a href="#" onClick="remove(this.parentNode)">...</a>
</div>

Reference: Node.parentNode, Node.removeChild

Further notes:

  • You better use a <button> instead of a link (<a>) for this kind of behaviour. A link has a distinct semantic meaning, it has to link somewhere. You can use CSS to style the button accordingly.
  • Event handlers are better added via JavaScript itself and not as an HTML attribute.

Upvotes: 24

Related Questions