简体   繁体   中英

how to delete an element that created in memory by using javascript

here is my situation

I don't want to insert the vdom to the body DOM like bellow codes showing, by the way.

  // vdom 
  const alink = document.createElement('a');
  document.body.appendChild(alink);
  alink.click();
  document.body.removeChild(alink);


const virtualDomConvert = (filename = ``) => {
  const svg = document.querySelector(`[id="live_map_svg"]`);
  const clone = svg.cloneNode(true);
  clone.id = 'vdom_svg';
  // autoRemoveAttributes(clone);
  const html = clone.outerHTML;
  // add xml namespace, support browser open preview
  const xml = `
    <?xml version="1.0" encoding="UTF-8"?>
    ${html}
  `.trim();
  const alink = document.createElement('a');
  alink.setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml));
  alink.setAttribute('download', filename);
  alink.style.display = 'none';
  const vdom = document.createElement(`div`);
  vdom.appendChild(alink);
  alink.click();
  vdom.removeChild(alink);  
  // ❓ how to delete vdom ???
  // vdom.remove();
  // vdom.parentElement.removeChild(vdom);
}

I had tried some methods, but still not working.

在此处输入图片说明

refs

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove

solution

I finger out that vdom just is in the JS environment, not in the real DOM context, so it's very easy to remove the vdom .

const log = console.log;

const virtualDomConvert = (filename = ``) => {
  const svg = document.querySelector(`[id="live_map_svg"]`);
  const clone = svg.cloneNode(true);
  clone.id = 'vdom_svg';
  // autoRemoveAttributes(clone);
  const html = clone.outerHTML;
  // add xml namespace, support browser open preview
  const xml = `
    <?xml version="1.0" encoding="UTF-8"?>
    ${html}
  `.trim();
  const alink = document.createElement('a');
  alink.setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml));
  alink.setAttribute('download', filename);
  alink.style.display = 'none';
  const vdom = document.createElement(`div`);
  vdom.appendChild(alink);
  alink.click();
  vdom.removeChild(alink);
  log(`vdom`, vdom);
  setTimeout(() => {
    delete this.vdom;
    log(`deleted vdom`, vdom);
  }, 3000);
}

as the screenshot shows

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM