Using Methods
createElement()
Using The proper way to create HTML with JavaScript is to use the createElement()
function. While best practice states that this is the preferred technique, due to its significantly better performance, it is also much more complex and difficult to use for novice developers. Furthermore, real-world benefits are marginal.
Creating HTML Element
The createElement()
method creates an HTML element with a specified tag name. The new element will have all of the properties and methods of elements retrieved from the DOM. However, the new element will only exist in JavaScript, as it has yet to be inserted into the HTML.
const $about = document.createElement('a')
$about.href = 'about.html'
$about.textContent = 'About'
Inserting HTML Element
Note
These techniques of inserting HTML elements will NOT work with template literals discussed in the previous section.
When using the createElement()
, there are two common methods for inserting elements into HTML: appendChild()
and insertBefore()
.
appendChild()
method
The The appendChild()
method adds a node to the end of a specified parent. With appendChild()
the parent element calls the method, and the new element is passed as a function parameter.
insertBefore()
method
The The insertBefore()
method will insert an element before a specified child of a specified parent. With insertBefore()
the parent element calls the method, and the new element is passed as the first function parameter and the child element to insert before will be the second element.