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')
.width = 400;
source.height = 400;
source.getContext("2d").fillRect(20,20,150,150)
source//DOES NOT WORK
= source
target }
//Silent failure
const modDom = (target: HTMLCanvasElement) => {
const source = document.createElement('canvas')
.width = 400;
source.height = 400;
source.getContext("2d").fillRect(20,20,150,150)
source//DOES NOT WORK
Object.assign(target,source)
}
//Meh?
const modDom = (target: HTMLCanvasElement) => {
const source = document.createElement('canvas')
.width = 400;
source.height = 400;
source.getContext("2d").fillRect(20,20,150,150)
source
//GOOD? Sometimes this fails when dealing with Webgl
.replaceWith(source);
target }
Best way is just to modify it directly
//GOOD
const modDom = (target: HTMLCanvasElement) => {
// target = document.createElement('canvas')
.width = 400;
target.height = 400;
target.getContext("2d").fillRect(20,20,150,150)
target
}