简体   繁体   中英

How to parse and extract CSS selectors as strings?

What is the simplest way to extract css selectors as strings?

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

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.

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
  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....

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

Is that what you're looking for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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