Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector for all elements beginning with app- prefix

Tags:

css

sass

angular

I'm trying to target all app- prefixed elements in my Angular application. Does anyone know a method in SCSS or vanilla CSS to target elements this way?

Please don't recommend using class or attribute targeting like [class^="app-"] I'm trying to avoid adding them.

like image 509
Ben Racicot Avatar asked Dec 17 '25 14:12

Ben Racicot


2 Answers

As far I know there 's no solution in css but in sass you can use list to store your components name and loop throw the list and create the desire selector.

but with this way you have to add the components name manually

$component-list : 'home','admin' , 'other';
$prefix : 'app';


@each $c in $component-list {
  #{$prefix}-#{$c}{
   color:red;
  }
}

stackblitz demo

like image 194
Muhammed Albarmavi Avatar answered Dec 20 '25 03:12

Muhammed Albarmavi


There's no such CSS selector. As you suggest, you can only do it with an attribute selector and ^=.

An alternative would be to use JavaScript:

const components = Array.prototype.filter.call(
  document.querySelectorAll('*'),
  e => e.tagName.toLowerCase().startsWith('app-')
)

You could now easily do components.forEach(cmp => cmp.classList.add('__angular-component')), and then from CSS do .__angular-component { background: red } or whatever.

like image 28
Lazar Ljubenović Avatar answered Dec 20 '25 03:12

Lazar Ljubenović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!