How to parse and extract CSS selectors as strings?

Tags: javascript,css,regex,css-selectors

Problem :

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

Given this as input:

#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']

Solution :

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("~~~");


    CSS Howto..

    How to have dots as horizontal separator with inline text like in this screenshot?

    how to draw a configurable pie chart in css

    How to apply css styles to a tag?

    how to combine multiple css class selectors for jquery buttonset?

    layout - show the latter coded div at top without absolute positioning

    How do i add a background image to my header?

    How to modify the CSS Properties (height width) of a div element via JQuery?

    How to define CSS styles if Javascript is turned off? [duplicate]

    Show or hide div based on selected value

    How to create icons like font awesome

    How do you style Wordpress sub-menus with CSS?

    How can I use a different CSS using jQuery?

    How to use Javascript to close css drop down menu on outside click?

    How to get the element position after css-translation

    How to make border for UL if Li has style “float:left;”?

    How to add scrollable tooltip HTML?

    Showcase the first n-items in a bootstrap grid

    How to vertically align numbers of ol?

    How to test .css file for syntax errors?

    how to search with GET method in MVC

    How can I display links in 2 rows?

    Table cells without borders having white lines - how do I disable them?

    How to use javascript/css to navigate through a pure css carousel/slideshow?

    How might I get an element's border color value using jQuery?

    How to set the maximum height of CSS images?

    How to keep floated element from affecting “text-align: center” text?

    How do I make punch-through transparent text in HTML/CSS?

    how to make nested flexboxes work

    How to set two divs side-by-side with the same height?

    how to change the css in td on mouse click using javascript