上間ウェブ店

【スニペット】javascript(es6)

2019/06/12

jsのes6記法のスニペットです。脱jqueryしたばっかりであんまり覚えてないのでコピペ用です。
ちなみに、webpackでビルドする時に付く設定なのでセミコロンは省略しています。

定義いろいろ

// 定数
const constant = document.querySelector('.constant') // 1つのdomを取得
const constants = document.querySelectorAll('.constant') // 同class名のdomを複数取得

// 変数
let i = 0

// 関数
const dosomething = () => {
  console.log('fired!!')
}

発火

constant.addEventListener('click', dosomething)

Array.from(constants).forEach((e) => {
  e.dosomething()
})

DOM操作系

DOM作成

const parent = document.createElement('div')
const child1 = document.createElement('h1')
const child2 = document.createElement('h2')
const child3 = document.createElement('h3')
const child4 = document.createElement('p')

DOM挿入

append()

appendは上から順番に追加します。文字列も追加可能。(テキストノードなのでhtmlタグを文字列として挿入は不可)

parent.append(child1)
parent.append(child2, child3, child4)
parent.append('append text')
/* 出力結果
<div>
  <h1></h1>
  <h2></h2>
  <h3></h3>
  <p></p>
  append text
</div>
*/

prepend()

prependはappendの逆のイメージ。

parent.prepend(child1)
parent.prepend(child2, child3, child4)
parent.prepend('prepend text')
/* 出力結果
<div>
  prepend text
  <h2></h2>
  <h3></h3>
  <p></p>
  <h1></h1>
</div>
*/

before()

parent.before(child1)
parent.before(child2, child3, child4)
/* 出力結果
<h1></h1>
<h2></h2>
<h3></h3>
<p></p>
<div></div>
*/

after()

parent.after(child1)
parent.after(child2, child3, child4)
/* 出力結果
<div></div>
<h2></h2>
<h3></h3>
<p></p>
<h1></h1>
*/

DOM削除

parent.after(child1)
parent.after(child2, child3, child4)
parent.remove()
/* 出力結果
<h2></h2>
<h3></h3>
<p></p>
<h1></h1>
*/

class操作

const element = document.querySelector('.element')
element.classList.add('element') // 追加
element.classList.remove('element') // 削除
element.classList.toggle('element') // toggle
element.classList.contains('element') // クラスがあるかどうか(true or false)