Home > database >  Does element.replaceChildren() function work with duplicate values, or what is stopping this from wo
Does element.replaceChildren() function work with duplicate values, or what is stopping this from wo

Time:04-29

currently i am trying to replace an elements children with the same value in an array
e.g:

const e = document.createElement("div");
e.className = "e";
e.innerHtml = "test ";
const a = [e, e, e];
// test is appearing only once instead of multiple times
document.body.replaceChildren(...a);

my code is this:

    class MockElement {
        constructor(className, children = []) {
            this.element = document.createElement("div");
            this.className = className;
            this.children = children;
            this.element.className = className;
            console.log(Array(children))
            if (children) this.element.replaceChildren(...Array(children));
        };
        replaceChildren(c) {
            this.children = c;
            this.element.replaceChildren(...c);
        };
    };

    //const wrapper = document.getElementById("centirdle-boards");



    const fill = (c, t) => {
        // init new array
        let a = new Array();
        // loop through {t} times, adds new copy of {c} to the array each time
        for (let j = 0; j < t; j  ) a.push( c );
        return a;
    };

    const h = new MockElement("h");
    // only seeing one of them
    document.body.replaceChildren(...fill(h.element, 5))

currently the fill function works fine and as intended
the mock element class also works fine

CodePudding user response:

JavaScript objects are references. This means that there is only a single h.element in the memory of your whole program, so if you tell the DOM to replace children with h.element 5 times, it will only insert it once because it is five references to a single element.

You must create multiple elements.

With your code example, that would look like this:

// Calls `document.createElement` five times total
const elements = new Array(5)
  .fill(null)
  .map(() => new MockElement("h").element); 

document.body.replaceChildren(...elements);

Check out this article to learn more: https://dmitripavlutin.com/value-vs-reference-javascript/

  • Related