Adding and Removing Elements
here are some methods, properties, and attributes you can use to add or remove elements in the DOM:
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);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);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);replaceChild(): This method replaces a child node with a new node.
Example:
insertBefore(): This method inserts a new node before a specified reference node as a child of a specified parent node.
Example:
innerHTML: This property sets or returns the HTML content of an element.
Example:
outerHTML: This property sets or returns the HTML content of an element, including the element itself.
Example:
cloneNode(): This method creates a copy of a node, including all of its attributes and descendants.
Example:
attributes: This property returns a live collection of attributes of an element.
Example:
hasAttribute(): This method returns true if an element has a specified attribute, otherwise it returns false.
Example:
setAttribute(): This method sets the value of an attribute on an element.
Example:
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