Search code examples
javascriptcsscss-selectorsnode-html-parser

Are meta sequences and quantifiers available in CSS selectors?


I am expecting that below code will capture all element that have style attributes begins with background: url(: or "background-image: url(.

import type { HTMLElement } from "node-html-parser";

const rootHTML_Element: HTMLElement = /* ... */;

for (
  const variadicElement of
      this.rootHTML_Element.querySelectorAll("[style*=\"background: url(\"]").
          concat(this.rootHTML_Element.querySelectorAll("[style*=\"background-image: url(\"]"))
) {
  // ...
}

(I am using the node-html-parser (it means, for Node.js), but I suppose that querySelectorAll in Browser JavaScript has same behavior).

Above code works in exact match case, but for example, if to there no space between background: and url, it will not work. To solve this problem, the meta sequences and quantifiers are required. If it was normal regular expression, the solution was :

style="background(?:-image)?:\s*url\(

How to get same effect for CSS selectors?


Solution

  • As mentioned by CBro regex is not an option. You could do something like this (you need to include white space etc. in your selectors)

    Note! the "i" at the end makes the selector case-insensitive

    :is( 
      /* note the white space must match */
      [style*="background-image: url(" i], 
      [style*="background-image:url(" i], 
      [style*="background: url(" i], 
      [style*="background:url(" i]) {
      outline: 2px solid;
    }
    
    div {
      margin: .25rem;
      padding: .25rem;
    }
    
    div::after {
      content: ': <div style="' attr(style) '">';
    }
    <div style="color: green; background: url(...)">Should Match</div>
    <div style="color: green; background:url(...)">Should Match</div>
    
    <div style="color: darkred; background: tomato">Shouldn't Match</div>
    
    <div style="color: green; BACKGROUND-image: url(...) ">Should Match</div>
    <div style="color: green; background-image:url(...) ">Should Match</div>