Search code examples
javascriptjquerygoogle-chrome-extensionmutation-observers

Mutation Summary Library: How to append html elements to added elements


I'm using Mutation Summary library to observe when a particular type of elements have been added and then append my html element to each of them:

var observer = new MutationSummary({
      callback: theNextPageLoaded,
      queries: [{
           element: "li.sweet"
      }]
});

function theNextPageLoaded(summaries) {
    var sc = summaries[0],
    sc_length = sc.added.length,
    btn = $('<button>', {
          class: 'my_btn',
          text: 'Please work!'
        });

    sc.added.forEach(function(newEl) {
      newEl.appendChild(btn);
      console.log(typeof(newEl));  //newEl's type is 'object'
    });
}

Code above is not working. I'm not sure I can even use appendChild on an object. Any help would be appreciated!


Solution

  • Your problem is mixing together "bare" DOM elements from Mutation Summary response and jQuery elements. Pure DOM appendChild does not understand your jQuery-wrapped btn.

    So, you need to make them both to be the same type:

    $(newEl).append(btn); // jQuery
    newEl.appendChild(btn.get(0)); // pure DOM
    

    Either works, but the first one is probably more idiomatic.