Search code examples
javascripthtmlappendchildremovechild

How to restrict html tag attribute validation?


Hi have create html element like below:

var element = document.createElement('div');
element.innerHTML = `<img src="fail" onerror="alert();" />`;
element.setAttribute('id', 'check');
document.body.append(element);

// removed element from DOM
 element.parentNode.removeChild(element);

When you run this code, you will see console error like below:

GET https://stacksnippets.net/fail 404 (Not Found)

Is there any sugestion to resolve this console error?


Solution

  • i tried lke below and resolve my pblm

     private static removeElement(): void {
             // Removes an element's attibute to avoid html tag validation
             let nodes: HTMLCollection = this.wrapElement.children;
             for (let j: number = 0; j < nodes.length; j++) {
                 let attribute: NamedNodeMap = nodes[j].attributes;
                 for (let i: number = 0; i < attribute.length; i++) {
                     this.wrapElement.children[j].removeAttribute(attribute[i].localName);
                 }
             }
        }