简体   繁体   English

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

[英]How to parse and extract CSS selectors as strings?

What is the simplest way to extract css selectors as strings? 将CSS选择器提取为字符串的最简单方法是什么?

Given this as input: 鉴于此作为输入:

#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}

How can I get a list of selectors such as this: 我如何获得这样的选择器列表:

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

Define "input. If that's in a stylesheet that's been parsed by the browser, you can use the DOM Level 2 Style APIs to extract the CSS rules in your stylesheet and query them for selectors (though you may have to do comma-splitting yourself). 定义“输入。如果是在浏览器已解析的样式表中,则可以使用DOM Level 2样式 API提取样式表中的CSS规则并查询选择器(尽管您可能需要用逗号分隔) 。

If it's not parsed by the browser but is provided as input via some other mechanism, you might be able to use JSCSSP (a CSS parser in JavaScript) to parse the input. 如果浏览器未解析它,但通过其他机制将其作为输入提供,则您可以使用JSCSSP (JavaScript中的CSS解析器)来解析输入。

Here is the solution I ended up with: 这是我最终得到的解决方案:

  1. Replace the curly braces including its contents with some unique characters. 用一些独特的字符替换大括号,包括其内容。 Regex was picked up from here Matching CSS Selectors with a Javascript RegExp 正则表达式是从这里获取的,带有Java RegExp的CSS选择器匹配
  2. Split the list at those unique characters. 将列表拆分为那些唯一的字符。

Just wanted to post it here for documention: 只是想将其发布在此处进行记录:

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);

WARNING: Waporcode, I haven't tested this, but I've used something like this before.... 警告:Waporcode,我没有测试过,但是我以前使用过类似的东西。

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

Is that what you're looking for? 那是您要找的东西吗?

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

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