Adding and Removing Elements

here are some methods, properties, and attributes you can use to add or remove elements in the DOM:

  1. createElement(): This method creates a new HTML element specified by the tagName argument. It returns a new Element object, which can then be appended to the DOM.

Example:

javascriptCopy codeconst newDiv = document.createElement('div');
document.body.appendChild(newDiv);
  1. appendChild(): This method appends a node as the last child of a parent node.

Example:

javascriptCopy codeconst newDiv = document.createElement('div');
document.body.appendChild(newDiv);

const newPara = document.createElement('p');
newDiv.appendChild(newPara);
  1. removeChild(): This method removes a child node from its parent node.

Example:

javascriptCopy codeconst parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.removeChild(child);
  1. replaceChild(): This method replaces a child node with a new node.

Example:

  1. insertBefore(): This method inserts a new node before a specified reference node as a child of a specified parent node.

Example:

  1. innerHTML: This property sets or returns the HTML content of an element.

Example:

  1. outerHTML: This property sets or returns the HTML content of an element, including the element itself.

Example:

  1. cloneNode(): This method creates a copy of a node, including all of its attributes and descendants.

Example:

  1. attributes: This property returns a live collection of attributes of an element.

Example:

  1. hasAttribute(): This method returns true if an element has a specified attribute, otherwise it returns false.

Example:

  1. setAttribute(): This method sets the value of an attribute on an element.

Example:

  1. removeAttribute(): This method removes an attribute from an element. The attribute is specified as a string parameter.

Example:

This example removes the disabled attribute from the myElement element.

Last updated