Elements
Elements
Nodes vs Elements
EventTarget
└── Node
├── Document
├── Element
└── Window
EventTarget is the object stored by Event.target.
Creating
Node.cloneNode()
Returns a clone of Node which has no parent and is not part of the document, until it is added to another node that is part of the document. The optional deep paramater does nothing if Node is an img or other void element (ie not a container that can contain child elements).
Node.removeChild()
Unlike Node.cloneNode() the return value preserves the EventListener objects associated with it. The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.
Document: importNode()
To clone nodes to be used in another document, use importNode()
Node.cloneNode() seems a better choice if just using one document.
document.createElement
A new HTMLElement is returned if the document is an HTMLDocument, which is the most common case.
Deleting
Element.remove()
Removes the element from its parent node.
Unlike Node.removeChild(), it does not return a Node.
Inserting
Element.append(child1, child2, …)
Differences from Node.appendChild():
- Element.append() allows you to also append strings, whereas Node.appendChild() only accepts Node objects.
- Element.append() has no return value, whereas Node.appendChild() returns the appended Node object.
- Element.append() can append several nodes and strings, whereas Node.appendChild() can only append one node.
Element.prepend(child1, child2, …)
Element.before(child1, child2, …)
Element.after(child1, child2, …)
Element.insertAdjacentElement(position, element)
Updating
Element1.replaceWith(Element2)
An element can be replaced with several elements. Does not return a value.
Node.replaceChild(newChild, oldChild)
// Replace existing node sp2 with the new span element sp1
parentDiv.replaceChild(sp1, sp2);
The parameter order, new before old, is unusual. Element.replaceWith(), applying only to nodes that are elements, may be easier to read and use.
Query
Element.localName
eg “img” or “div”
Element.id
Returns "" if element has no id;
Node.parentElement
returns the DOM node’s parent Element, or null if the node either has no parent, or its parent isn’t a DOM Element.
Node.parentNode
always returns the parent node, which may be a Document or other node types.