Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove an element in Javascript without jQuery

Tags:

javascript

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

like image 753
a.m. Avatar asked May 23 '11 23:05

a.m.


People also ask

How do you remove an element in JavaScript?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

Is there a remove method in JavaScript?

Summary. Removing JavaScript Array items is important to managing your data. There is not a single 'remove' method available, but there are different methods and techniques you can use to purge unwanted array items.

What does remove () do JS?

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

How add and remove items in JavaScript?

The list items are added or removed using JavaScript functions addItem() and removeItem(). The list items are created using document. createElement() method and to create a text node, document. createTextNode() method is used and then this node is appended using appendChild() method.


1 Answers

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.
like image 100
Felix Kling Avatar answered Oct 23 '22 02:10

Felix Kling