【脱jQuery】append prepend after beforeを素のJavascriptで行う

脱jQueryの動きに際しまして、append prepend after beforeを素のJavascriptで行う方法について記します。

こちら色々な方法あるようですが、私が一番シンプルでわかりやすいと感じる方法を紹介します。



素のJavascriptのappend() prepend() after() before()

素のJavascriptにもappend prepend after beforeは用意されているようです。
document.createElementで生成したHTMLElementを引数に渡して追加する事ができます。

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)





素のJavascriptのappend() prepend() after() before()の難点

素のJavascriptのappend prepend after beforeにはひとつ難点がありまして、下記のようにHTML文字列を追加しようとすると、HTMLタグがそのまま表示されてしまいます。(2023年9月時点)

// HTMLタグがそのまま表示されてしまう
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>')





HTML文字列もappend() prepend() after() before()できるようにする

append prepend after beforeはNodeを引数に渡せばきちんとHTML要素としてDOMツリーに追加してくれるので、一度HTML文字列をNodeに変換して渡すという方法を採ります。

まず、下記のようにHTML文字列をNodeに変換してくれる関数を用意します。

function toNode(str) {
    return document.createRange().createContextualFragment(str)
}


そして、先ほどの関数を使用してHTML文字列をNodeに変換後append prepend after beforeする事で、きちんとHTML要素としてDOMツリーに追加する事ができます。

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







以上、素のJavascriptでappend prepend after beforeを行う方法でした。

スポンサーリンク

You can subscribe by SNS

スポンサーリンク

*