为了账号安全,请及时绑定邮箱和手机立即绑定

有没有什么方法可以选择DOM中不存在的带有JS的CSS类?

有没有什么方法可以选择DOM中不存在的带有JS的CSS类?

凤凰求蛊 2021-05-14 17:15:36
是否可以选择仅在其文件中注册但在DOM中不存在的class带有JS的CSS ?var elem = document.getElementsByClassName('class2')[0],    getStyle = window.getComputedStyle(elem),    value = getStyle.getPropertyValue('top');console.log(value);// Can't get the value of class2 because it doesn't exist in DOM. .class1 {  top: 10px;}.class2 {  top: 20px;}<div class="class1">  top</div>像这个例子一样,选择没问题,.class1因为它存在于元素中的DOM中。但是我想访问.class2DOM内部不存在的。有什么方法可以做到这一点?
查看完整描述

2 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

访问此类元素的唯一可能方法是预先引用该元素或其父元素之一。通常的方法是使用从创建的元素引用document.createElement,或使用创建元素的任何方式:


const element = document.createElement('div');

element.className = 'class2';


// element is not attached to the DOM, but you can still reference it here


// you can also retrieve elements created by assigning to the innerHTML of another element:

element.innerHTML = '<div class="class2"></div>';

const element2 = element.children[0];


// element2 is not attached to the DOM, but you can still reference it here

如果看不到元素的创建位置,则这些方法将无效。在这种情况下,您唯一的选择是在创建元素的脚本运行之前,对可以创建元素的各种方法进行猴子修补(例如createElementinnerHTMLsetter,outerHTMLsetter等),但这总是一个非常糟糕的主意,除非没有其他方法选项(例如,如果您正在编写用户脚本)。


查看完整回答
反对 回复 2021-05-27
  • 2 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信