![脱jQueryの代替コードの記事はわかりづらいものが多いので注意](https://iwb.jp/wp-content/uploads/2023/01/javascript-jquery-alternative-code-articles-are-difficult-to-understand.png)
脱jQueryの代替コードがわかりづらい
日本版Googleで検索した際に脱jQueryの代替コードの記事が表示されることがある。
例えば$.after()の場合、記事AではinsertAdjacentElementを使うよう書かれている。
const foo = document.querySelector('.foo')
const bar = document.querySelector('.bar')
foo.insertAdjacentElement('afterend', bar)
記事Bでは以下のようになっていました。
const foo = document.querySelector('.foo')
const bar = document.querySelector('.bar')
foo.parentNode.insertBefore(bar, foo.nextElementSibling)
うーん、わかりづらい😅
$.after()などは.after()で代替可能
$.after()などは.after()のメソッドがあるので、前述のような書き方をしなくても以下のようにシンプルに書けます。
const foo = document.querySelector('.foo')
const bar = document.createElement('strong')
bar.textContent = 'sample'
foo.after(bar)
append(), before(), children(), closest(), prepend(). remove()などもそのまま使えるのに、わかりづらい書き方をした代替コードを記載しているWebサイトがあるので注意が必要です。