The DOM offers various methods to edit the nodes of the page and alter the document tree.
With
document.createElement()
: creates a new Element Nodedocument.createTextNode()
: creates a new Text Node
you can create new elements, and add them to the DOM elements you want as children, by using document.appendChild()
:
const div = document.createElement('div')
div.appendChild(document.createTextNode('Hello world!'))
first.removeChild(second)
removes the child node “second” from the node “first”.document.insertBefore(newNode, existingNode)
inserts “newNode” as a sibling of “existingNode”, placing it before that in the DOM tree structure.element.appendChild(newChild)
alters the tree under “element”, adding a new child Node “newChild” to it, after all the other children.element.prepend(newChild)
alters the tree under “element”, adding a new child Node “newChild” to it, before other child elements. You can pass one or more child Nodes, or even a string which will be interpreted as a Text node.element.replaceChild(newChild, existingChild)
alters the tree under “element”, replacing “existingChild” with a new Node “newChild”.element.insertAdjacentElement(position, newElement)
inserts “newElement” in the DOM, positioned relatively to “element” depending on “position” parameter value. See the possible values.element.textContent = 'something'
changes the content of a Text node to “something”.
Lessons in this unit:
0: | Introduction |
1: | The `window` object |
2: | The `document` object |
3: | Types of nodes |
4: | Traversing the DOM |
5: | ▶︎ Editing the DOM |
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!