如何解析和提取CSS选择器作为字符串

How to parse and extract CSS selectors as strings?

本文关键字:字符串 选择器 CSS 何解析 提取      更新时间:2023-09-26

提取css选择器作为字符串的最简单方法是什么?

输入:

#article{width:690px;overflow:hidden}
#article h2:first-child a{text-decoration:none}
#works .project p:last-child{margin-top:20px;font-size:13px}
#works .project img, #works .info img{width:680px;min-height:400px;border:1px dotted #ccc;margin-bottom:40px}

如何获得选择器列表,如:

var selectors = ['#article','#article h2:first-child a','#works .project p:last-child','#works .project img']

定义"输入"。如果是在浏览器解析过的样式表中,您可以使用DOM Level 2 Style api提取样式表中的CSS规则,并查询选择器(尽管您可能必须自己执行逗号分割)。

如果它没有被浏览器解析,而是通过其他机制作为输入提供,那么您可能可以使用JSCSSP (JavaScript中的CSS解析器)来解析输入。

这是我最终的解决方案:

  1. 用一些唯一的字符替换包含其内容的花括号。用Javascript RegExp
  2. 匹配CSS选择器
  3. 在这些唯一字符处拆分列表。

只是想把它贴在这里作为文档:

var css = "#article[type=x]{width:690px;overflow:hidden}#article h2:first-child a{text-decoration:none}#works .project p:last-child{margin-top:20px;font-size:13px}#works .project img, #works .info img{width:680px;min-height:400px;border:1px dotted #ccc;margin-bottom:40px}"
var found = css.replace(/{([^}]*)}/gm,"~~~").split("~~~");
document.write(found);

警告:Waporcode,我还没有测试过这个,但我之前使用过类似的东西....

    document.styleSheets[0].cssRules[0].selectorText

这是你想要的吗?