[Diching jQuery]Using append,prepend,after,before in plain JavaScript

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')


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

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.


That is all. It was about how to perform append(), prepend(), after(), before() operations using plain JavaScript.

Sponsored Link

You can subscribe by SNS

Sponcerd Link