0

Is it possible to select a CSS class with JS which is registered only in its file, not exist in DOM?

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>

Like this example, There's no problem to select the .class1 because it's exist in DOM within an element.

But I want to access the .class2 which doesn't exist inside of DOM.

Are there any ways to do this?

4

2 回答 2

1

访问此类元素的唯一可能方法是事先引用它或其父元素之一。通常的方法是使用从创建的元素引用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 等),但这几乎总是一个非常糟糕的主意,除非没有其他方法选项(例如,如果您正在编写用户脚本)。

于 2019-05-12T05:45:43.747 回答
1

XY 问题在这里...您不愿意获取元素,而是样式表中设置的值。

即使这可能是可能的(它是,但是非常复杂),这种方法也有一个很大的缺陷:因为 CSS 规则存在并不意味着它会被应用

例如,在您的情况下,该.class2规则确实存在并且处于活动状态,但是,由于没有元素与该规则匹配,因此它不会产生任何影响。
同样的,即使一个元素确实符合这条规则,它也很可能被其他规则覆盖:

console.log(
  getComputedStyle(
    document.querySelector('.class2')
  ).getPropertyValue('top')
); // "10px"
#foo { top: 10px };
.class2 { top: 50px; }
<div class="class2" id="foo"></div>

所以,是的,你可以得到 CSSRule 的设置值:

const matching_rules = [...document.styleSheets].reduce((matched, sheet) => {
  [...sheet.cssRules].forEach( r => {
      if(r.selectorText && r.selectorText.includes('.class2'))
        matched.push(r.style.top);
  });
  return matched;
}, []);
console.log(matching_rules);
.class2 { top: 50px; }

但是再一次,这真的getComputedStyle没用,而且大多数时候,你只需要在你的元素附加到 DOM 后调用它(之前调用它是没有用的,因为没有 CSS 规则应用于未显示的元素.

const elem = document.createElement('div');
elem.classList.add('class2');
console.log('matches:', elem.matches('.class2')); // true
const comp = getComputedStyle(elem);
console.log('computed top:', JSON.stringify(comp.getPropertyValue('top'))); // "" (the default)
.class2 {
  top: 50px;
}

于 2019-05-12T06:43:04.367 回答