JS Functions that Replace HTMLElement

Posted on October 2, 2021
Tags: javascript

Common method is a function that replaces an existing DOM element with the one we created in the function. Common mistake is to simply assign the pre-existing target Element with the one we built in the function.

//Silent failure
const modDom = (target: HTMLCanvasElement) => {
    
    const source = document.createElement('canvas')
    source.width = 400;
    source.height = 400;
    source.getContext("2d").fillRect(20,20,150,150)
    //DOES NOT WORK
    target = source  
}
//Silent failure
const modDom = (target: HTMLCanvasElement) => {
    
    const source = document.createElement('canvas')
    source.width = 400;
    source.height = 400;
    source.getContext("2d").fillRect(20,20,150,150)
    //DOES NOT WORK
    Object.assign(target,source)    
}
//Meh?
const modDom = (target: HTMLCanvasElement) => {
    
    const source = document.createElement('canvas')
    source.width = 400;
    source.height = 400;
    source.getContext("2d").fillRect(20,20,150,150)

    //GOOD? Sometimes this fails when dealing with Webgl
    target.replaceWith(source);     
}

Best way is just to modify it directly

//GOOD 
const modDom = (target: HTMLCanvasElement) => {
    
    // target = document.createElement('canvas')
    target.width = 400;
    target.height = 400;
    target.getContext("2d").fillRect(20,20,150,150)
    
}