Search code examples
javacsscss-parsing

How to get selector inside @media?


I'm trying to parse css by using CSSParser For example, I have css:

 final String css = "@media screen and (color) { h1 { color: red } }";

I want to get this part:

{ h1 { color: red } }

But when I'm doing it by using mediaList

    final CSSStyleSheet sheet = parse(css);
    final CSSRule cssRule = sheet.getCssRules().item(0);
    final MediaList mediaList = ((CSSMediaRuleImpl) cssRule).getMedia();

I get only

Output: screen and (color)

Maybe somebody faced with this issue?


Solution

  • If anyone needs answer :

    @Test
    public void testCSSParser2() throws IOException {
        String css = "@media only screen and (max-width: 600px) {body { background-color: lightblue } h1 { color: red } }";
        InputSource source = new InputSource(new StringReader(css));
        CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
        CSSStyleSheet sheet = parser.parseStyleSheet(source, null, null);
        CSSRuleList rules = sheet.getCssRules();
        for (int x = 0; x < rules.getLength(); x++) {
            final CSSMediaRule mediaRule = ((CSSMediaRule) rules.item(x));
            CSSRuleList mediaRules = mediaRule.getCssRules();
            for (int y = 0; y < mediaRules.getLength(); y++) {
                final CSSRule rule = mediaRules.item(y);
                System.out.println(rule.getCssText());
    
            }
        }
    
    }