Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active July 8, 2022 23:32
Show Gist options
  • Save yano3nora/7f04004e4479dd0bb4045439122a809e to your computer and use it in GitHub Desktop.
Save yano3nora/7f04004e4479dd0bb4045439122a809e to your computer and use it in GitHub Desktop.
[js: Mutation Observer] #js
/**
* https://ja.javascript.info/mutation-observer
*/
const origin = document.querySelector('p#origin')
const copy = document.querySelector('p#copy')
// origin の変更を検知して innerText を copy へ転記、的な...
const obs = new MutationObserver(mutations => {
// mutations に変更内容の詳細が配列で入ってる感じ
// 正直ここで origin を api から読み取ったほうが見やすいけど
// options 次第で old value とったりとか凝ったこともできるぽい
copy.innerText = mutations.at(-1).target.innerText
}).observe(origin, { childList: true })
// 購読破棄
obs.disconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment