Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@otome0927@github

MutationRecordを使用してdomの追加からclass変更までを監視する

More than 3 years have passed since last update.

データのロード時間の計測(ロード中表示用のDOMを監視)とか、Seleniumでテストするときにロードを待つとか使えそうな感じ。
人に聞かれたときにうまく答えられなかったので、次は答えられるように記載。

参考資料
存在していないDOM要素を検知する方法
https://developer.mozilla.org/ja/docs/Web/API/MutationObserver
JavaScript初級者から中級者になろう - 十七章第一回 MutationObserver

var observeTo = "foo";

var documentObserver = function() {
    var option = { childList: true, subtree: true, attributes:true };

    var observer = new MutationObserver(findClassListener);
    observer.observe(document.body, option);

    return observer;
};

var findClassListener = function(mutation) {

    mutation.forEach(function(m) {
        var nodes = m.addedNodes;
        var targetNode = m.target;
        for(i=0; i<nodes.length; i++) {
            if (nodes[i].classList.contains("foo")) {
                console.log("A " + observeTo + " class DOM is generated !");
            }
        }
        if(nodes.length == 0 && targetNode.classList.contains('change')){
            console.log("changed!!!");
        }
    });
};

documentObserver();
var rendered = document.createElement("div");
rendered.className += ' ' + "foo";
document.body.appendChild(rendered);
window.setTimeout(function(){
  console.log("timeout");
  var renderDiv = document.getElementsByClassName('foo')[0];
  renderDiv.className = 'change';
},1000);
1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?