Home > Back-end >  Get CSS content from a rule using regex
Get CSS content from a rule using regex

Time:02-08

For example, I have a stylesheet:

.foo {
 background-color: #fff;
}

.bar {
 font-size: 20px;
}

What regex could I use to get background-color: #fff; from .foo?

UPD: There could be anything in .foo so no need to hard code background-color

CodePudding user response:

If your styles are written in the CSS file, you need to get the computed style. To do so, you can use getComputedStyle.

In this case you can get all styles, no needs to use regex.

const element = document.querySelector('.foo');
const style = getComputedStyle(element);
console.log('styles', style.padding, style.background, style);
.foo {
  background: tomato;
  padding: 1rem;
}
<div >Text</div>

CodePudding user response:

Most of regex characters are string literals, and a valid string is also a valid regex if it does not include meta characters, so you can use this:

enter image description here

If you want to get any value for the background color you can use this:

enter image description here

If you want to get the background color only for .foo you can use a positive lookbehind, like this:

enter image description here

If you want to match any css rule with any value that comes before a .foo space { newline space you can use something like this:

enter image description here

Just note, that this regex is specifically designed for your usecase and might need to be generalized for be able to fit in with more examples.

  •  Tags:  
  • Related