Js after() not working properly

Hello, I have an issue with the after() method (inserting node after another one).

index.html :

<!DOCTYPE html>
<html>
<head>
  <script src="test.js"></script>
</head>
<body>
  <div>
    <div>
      <a id="button1">button1</a>
    </div>
  </div>
  <div>
    <div>
      <div>
        <a id="button2">button2</a>
      </div>
    </div>
  </div>
</body>
</html>

JS in PS plugin :


document.addEventListener("DOMContentLoaded", () => {
    let b1 = document.getElementById("button1");
    b1.addEventListener("click", (e) => {
        let div = e.target.parentElement.parentElement;
        let div2 = document.createElement("span");

        div.after(div2);
    });

    let b2 = document.getElementById("button2");
    b2.addEventListener("click", (e) => {
        let div = e.target.parentElement.parentElement;
        let div2 = document.createElement("span");

        div.after(div2);
    });
});

This works well for both buttons in chrome.
It works only for button1 in a PS plugin.

Is there something I don’t see, or is after() method buggued ?

Thank you !

Notes : insertBefore() has the same problem.

I have another way to do the same thing, by replacing :
div.after(div2) with : div.insertAdjacentElement(“afterend”, div2)

@efreetcs There seems to be an issue with after() in UXP. The placement of the newly added div in the button1 case is also incorrect. I have created a ticket to fix this in UXP (Ticket ID: 21953). I would suggest you use insertBefore for now in this way.

<script>
    document.addEventListener("DOMContentLoaded", () => {
    let b1 = document.getElementById("button1");
    b1.addEventListener("click", (e) => {
        let div = e.target.parentElement.parentElement;
        let div2 = document.createElement("span");
        div2.innerHTML = "div 2 from button 1 click";
        div.parentElement.insertBefore(div2, div.nextSibling);
    });

    let b2 = document.getElementById("button2");
    b2.addEventListener("click", (e) => {
        let div = e.target.parentElement.parentElement;
        let div2 = document.createElement("span");
        div2.innerHTML = "div 2 from button 2 click";
        div.parentElement.insertBefore(div2, div.nextSibling);
    });
});
</script>

1 Like