Creating Elements
Creating New Elements
As we saw a preview of last week, before we can manipulate any object in the webpage, we need to select it first. In addition to selecting existing elements, we can also create new ones using document.createElement('NAME_OF_ELEMENT')
.
The snippet above creates a new element newHeading
but it is not yet part of the DOM. You can add it to the end of the page using document.body.appendChild(newHeading)
. document.body
is a handy shortcut for the <body>
tag.
You can also do targetElement.insertAdjacentElement(position, element)
to insert an element at the given position position
where position
is any of the following:
position
string
Where element
is inserted
"beforebegin"
before targetElement
"afterbegin"
as first child of targetElement
"beforeend"
as last child of targetElement
"afterend"
after targetElement
Last updated
Was this helpful?