DOM Manipulation in Mendix: Solving the Element-Not-Found Timing Bug - Mendix Forum

DOM Manipulation in Mendix: Solving the Element-Not-Found Timing Bug

0

Manipulating the DOM in Mendix?

Easy — until your script runs before the element even exists. 🧩


⁉️ When we try to add, move, or remove a widget/element on the canvas, only for your JS to silently fail with "element not found"?


That's not a logic issue — it's a timing issue.

The code ran before Mendix finished rendering the page.


The fix: MutationObserver ⚡ — a native browser API that watches the DOM and fires the moment your target element (and its children) actually shows up. No setTimeout guesswork needed.


Here's how to use it 👇
Step 1: Update the name of your widget that you want to target.


Step 2: Add the widget HTML snippet on the page you want to do the DOM manipulation.

and select the javascript option, here we will add our cutom JS code.



Step 3: Add the Mutation Observer API in your code.

This browser API will wait untill the DOM is completely rendered in the canvas.

Then it will trigger the funtion which we can use to manipulate the DOM.


const observer = new MutationObserver(() => {
    const source = document.querySelector(".mx-name-MovableHeader");
    const target = document.querySelector("mx-name-TargetHeader .tr");

    if (source && target) {
        while (source.firstElementChild) {
            target.appendChild(source.firstElementChild);
        }
        observer.disconnect(); // stop watching once done
    }
});

observer.observe(document.body, { childList: true, subtree: true });


Read this documentaion for more 😉


Posted
0 comments