Skip to content

How can only the new nodes be detected? #267

Description

@dswitzer

I've got what I think is a very basic example and what I'd think would be a common scenario, but I can't get it working the way I'd expect. I'm trying to detect where the new nodes were added so I can temporarily highlight the nodes so the user can see how their changes are visually affecting the rendering of a template (i.e. a live preview).

However, I'm having trouble getting this to work the way I want since changes that get applied often trigger unexpected nodes being added.

For example, take the following example:

source = "<div><p>a</p><p>b</p><p>c</p><p>d</p><p>e</p></div>";
target = "<div><p>a</p><p>b</p><p>c</p><div>!!!</div><p>d</p><p>e</p></div>";

// even having IDs on the elements is not helping
// source = '<div><p id="a">a</p><p id="b">b</p><p id="c">c</p><p id="d">d</p><p id="e">e</p></div>';
// target = '<div><p id="a">a</p><p id="b">b</p><p id="c">c</p><div id="new">!!!</div><p id="d">d</p><p id="e">e</p></div>';

let fromNode = parseHTML(source).querySelector("body")
  , toNode = parseHTML(target).querySelector("body")
;

morphdom(fromNode, toNode, {
  addChild: function(parentNode, childNode) {
    console.log("addChild => %o", childNode.outerHTML);
    parentNode.appendChild(childNode);
  }
});

function parseHTML(src){
  // var DOM = document.createRange().createContextualFragment(src);
  const parser = new DOMParser();
  const DOM = parser.parseFromString(src, "text/html");

  return DOM;
}

Visually it's clear that the only "change" to DOM would be to add in the <div>!!!</div> element between c and d, but when morpdom patches the DOM, the addChild outputs:

addChild =>  <div>!!!</div>
addChild =>  <p>d</p> 
addChild =>  <p>e</p>

As a general rule, I'm seeing everything after the insertion point trigger changes.

I've tried giving the elements IDs, but that makes no difference (see the commented code in the example). Using a MutationObserver isn't of much help, because if a node gets moved in the DOM, it triggers an event for the removal and adding to it's new location (even if it's just changing sibling positions).

How can I go about just targeting to do something just when the new <div>!!!</div> node is inserted?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions