为何设置display: none后ifx__alert-icon-wrapper仍存在于DOM中?
问题
我给ifx__alert-icon-wrapper元素设置了display: none,且确认没有给它添加show类,但为什么这个元素仍然存在于DOM中?
相关代码
<div class='ifx__alert-icon-wrapper'> <ifx-icon icon={this.icon}></ifx-icon> </div>
&__alert-icon-wrapper { display: none; &.show { position: relative; min-width: 48px; display: flex; justify-content: center; align-items: center; } }
DOM结构截图

解答
display: none的作用只是让元素在页面上不可见,它并不会将元素从DOM树中移除。元素依然会存在于HTML结构里,只是浏览器不会渲染它,也不会占据页面空间。
如果想要彻底把元素从DOM中移除,你需要用JavaScript来实现:
- 原生JS可以调用元素的
remove()方法,比如document.querySelector('.ifx__alert-icon-wrapper').remove() - 如果你用的是前端框架(比如React、Vue),可以通过条件渲染来控制元素是否生成,比如React里的
{condition && <div class='ifx__alert-icon-wrapper'>...</div>}
内容的提问来源于stack exchange,提问作者happy_story
相关产品推荐
相关产品推荐

