回答編集履歴

1

chousei

2022/10/04 10:23

投稿

yambejp
yambejp

スコア114845

test CHANGED
@@ -12,3 +12,29 @@
12
12
  ccc
13
13
  </div>
14
14
  ```
15
+
16
+ # 任意に書き換わる要素のテキストを監視
17
+ ノードを監視して変化したときに対応するならMutationObserverが一般的
18
+ ボタンをおすと1秒後にターゲットの文字が「hoge」に置き換わるが、監視をしているので大文字になるというサンプル
19
+ ```javascript
20
+ <script>
21
+ window.addEventListener('DOMContentLoaded', ()=>{
22
+ btn.addEventListener('click',()=>{
23
+ setTimeout(()=>target.textContent="hoge",1000);
24
+ });
25
+
26
+ const observer = new MutationObserver((mutations) => {
27
+ mutations.forEach((mutation) => {
28
+ const txt=mutation.target.textContent;
29
+ if(/[a-z]/.test(txt)){
30
+ mutation.target.textContent=txt.toUpperCase();
31
+ }
32
+ });
33
+ });
34
+ const config = {childList:true,characterData :true,subtree :true};
35
+ observer.observe(document.querySelector('#target'), config);
36
+ });
37
+ </script>
38
+ <span id="target">---</span>
39
+ <input type="button" value="btn" id="btn">
40
+ ```