简体   繁体   English

如何使用javascript删除在内存中创建的元素

[英]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 插入到主体 DOM 中。

  // 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 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 .我指出vdom只是在 JS 环境中,而不是在真正的 DOM 上下文中,所以很容易删除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如屏幕截图所示

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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