In the context of ditching jQuery, I would like to explain how to perform append(), prepend(), after(), before() operations using plain JavaScript.
There are several methods available for achieving this, but I will introduce the one I find the simplest and most comprehensible.
Plain Javascript’s append(), prepend(), after(), before()
It seems that plain JavaScript also provides append(), prepend(), after(), before().
You can use these methods by passing an HTMLElement generated with document.createElement() as an argument for inserting elements.
const appendEl = document.createElement('p')
const prependEl = document.createElement('p')
const afterEl = document.createElement('p')
const beforeEl = document.createElement('p')
document.querySelector('#output').append(appendEl)
document.querySelector('#output').prepend(prependEl)
document.querySelector('#output').after(afterEl)
document.querySelector('#output').before(beforeEl)
The drawbacks of plain Javascript’s append(), prepend(), after(), before()
There is one drawback to use append(), prepend(), after(), before() of plain JavaScript,.
When you attempt to add HTML strings as follows, the HTML tags are displayed as they are (as of September 2023).
// The HTML tags are displayed as they are
document.querySelector('#output').append('<p>append</p>')
document.querySelector('#output').prepend('<p>prepend</p>')
document.querySelector('#output').after('<p>after</p>')
document.querySelector('#output').before('<p>before</p>')
Enable HTML string usage for append(), prepend(), after(), before()
By passing a Node as an argument to append(), prepend(), after(), before(), they will correctly add it to the DOM tree as an HTML element.
Therefore, we adopt the approach of first converting HTML strings into Nodes before passing them.
First, prepare a function that converts HTML strings to Nodes as follows.
function toNode(str) {
return document.createRange().createContextualFragment(str)
}
By using the toNode function to convert HTML strings to Nodes before passing to append(), prepend(), after(), before() , you can then properly add them to the DOM tree as HTML elements.
document.querySelector('#output').append(toNode('<p>append</p><span>hoge</span>'))
document.querySelector('#output').prepend(toNode('<p>prepend</p>'))
document.querySelector('#output').after(toNode('<p>after</p>'))
document.querySelector('#output').before(toNode('<p>before</p>'))
That is all. It was about how to perform append(), prepend(), after(), before() operations using plain JavaScript.