Skip to content
Fix Code Error

Remove element by id

March 13, 2021 by Code Error
Posted By: Josh

When removing an element with standard JavaScript, you must go to its parent first:

var element = document.getElementById("element-id");
element.parentNode.removeChild(element);

Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?

Solution

element.remove()

The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So element.parentNode.removeChild(element) mimics exactly what is happening internally: First you go the parent node, then remove the reference to the child node.

As of DOM4, a helper function is provided to do the same thing: element.remove(). This works in 96% of browsers (as of 2020), but not IE 11. If you need to support older browsers, you can:

  • Remove elements via the parent node, as in the question,
  • modify the native DOM functions, as in Johan Dettmar’s answer, or
  • use a DOM4 polyfill.
Answered By: Anonymous

Related Articles

  • Table with table-layout: fixed; and how to make one…
  • How do i update a javascript variable as its value changes?
  • Form field border-radius is not working only on the…
  • List of Timezone IDs for use with FindTimeZoneById() in C#?
  • Why the REPL is not showing the full trace of the…
  • how to use canvas in JavaScript flappy bird code
  • How to create a game over screen for a basic HTML/JS game?
  • Javascript validate all checkboxes are selected
  • Polymer 2 dynamically merging templates
  • setTimeout function not working : javascript
  • Why doesnt my table sort my div variable in numerical order?
  • Ukkonen's suffix tree algorithm in plain English
  • Does moment.js allow me to derive a timezone…
  • getting text input from a form in react.js using Refs
  • how to add nodes and links do d3-force without enter
  • Avoid using document.getElementById with Backbone.js
  • Disabling a button upon condition in Google App script
  • What are the nuances of scope prototypal /…
  • Polymer 1.0 Trying to make a splitter which works…
  • How can I pass a wct test while rearranging children…
  • For-each over an array in JavaScript
  • Backbone.js Memory Management, Rising DOM Node Count
  • Difference between Node object and Element object?
  • Cast/initialize submodels of a Backbone Model
  • Pass props to parent component in React.js
  • Polymer Dom-Repeat Binding to Content
  • Sort table rows In Bootstrap
  • Vue delete child component
  • Js Calculation based on radio button, and some problems
  • How to import classes defined in __init__.py
  • Maximum XOR With an Element From Array | Leetcode
  • How to remember things when it comes to mixture of…
  • Generating a drop down list of timezones with PHP
  • Unknown template object error with handlebars 2.0 runtime
  • How can we deal with a data model containing child…
  • Backbone.js - Should nested Views maintain…
  • Executing elements inserted with .innerHTML
  • react-table has a issue with rendering in next.js
  • Generated row of table event listener not working instantly
  • javascript minesweeper issue with revealing tiles…
  • Convert array to nested JSON object - Angular Material tree
  • Checkout another branch when there are uncommitted…
  • load scripts asynchronously
  • adding child nodes in treeview
  • How do I keep only the first map and when the game…
  • Displaying the Dates that user have chosen from date input
  • nesting elements and dynamic content inside…
  • Set cursor position on contentEditable
  • How to remove an HTML element using Javascript?
  • Flappy bird code not working - JavaScript
  • Modified knapsack problem gets stuck in infinite loop
  • onClick function of an input type="button" not working
  • How does PHP 'foreach' actually work?
  • Iterator invalidation rules
  • How to find out what is referencing a detached DOM…
  • Perfomance issues with large number of elements in…
  • Setting DIV width and height in JavaScript
  • I made a game it should display two images when i…
  • Python File Error: unpack requires a buffer of 16 bytes
  • Printing Even and Odd using two Threads in Java
  • JavaScript TypeError: Cannot read property 'style' of null
  • What is a NullReferenceException, and how do I fix it?
  • How can building a heap be O(n) time complexity?
  • how to turn a recursive algorithms into an iterative one
  • Can I modify Vue.js VNodes?
  • Getting a "TypeError" when trying to validate a form
  • Unable to use helper classes within unit tests of a…
  • VueJS masonry layout
  • Java compare linked list with another file and…
  • Smart way to truncate long strings
  • Difference between DOM parentNode and parentElement
  • What does T&& (double ampersand) mean in C++11?
  • How to use Servlets and Ajax?
  • How to create new div dynamically, change it, move…
  • What does this symbol mean in JavaScript?
  • How to correct "TypeError: 'NoneType' object is not…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • What is the most efficient/elegant way to parse a…
  • How can I center all my contents in html?
  • SICP recursive let definition
  • How can I change an element's class with JavaScript?
  • data.table vs dplyr: can one do something well the…
  • How do you parse and process HTML/XML in PHP?
  • How to print binary tree diagram?
  • Simple pagination in javascript
  • Adding close button in div to close the box
  • jQuery Mobile: document ready vs. page events
  • XPath - Difference between node() and text()
  • Having trouble with my nav bar/header, It used to…
  • How is compiler inferring type on a generic method?
  • How to handle initializing and rendering subviews in…
  • The best way to calculate the height in a binary…
  • File to import not found or unreadable: compass
  • Haskell: ternary tree average, with nested `where`
  • Remove all child elements of a DOM node in JavaScript
  • Javascript change color of text and background to…
  • Data binding between sibling custom elements
  • Highlight a word with jQuery
  • Cannot read property 'nodeName' of null at…
  • How to implement a basic iterative pushdown…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

Next Post:

How to initialize an array in Java?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error