Martin Verdejo
Martin Verdejo

Reputation: 1369

sass - Get attribute of selected element using scss

I'm trying extract the background images of similar buttons into a sass map like the following:

$icons: (
  users: '../../assets/files/images/admin/[email protected]',
  cms: '../../assets/files/images/admin/[email protected]',
  rules: '../../assets/files/images/admin/[email protected]',
  data: '../../assets/files/images/admin/[email protected],',
  setting: '../../assets/files/images/admin/[email protected]',
  logout: '../../assets/files/images/admin/[email protected]'
);

Is there a way for me to dynamically generate styling for each of my buttons by accessing their div#id attribute and using that to access this hash?

My goal is to simplify my sytling to something that looks like the following:

div {
  background-image: url(map-get($icons, $this.id));
}

I'm looking for the correct syntax to replace $this.id.

Upvotes: 1

Views: 375

Answers (1)

Ari
Ari

Reputation: 1703

Sass doesn't have a concept for this. But If you know all your button ids, you can put them in a map or a list and iterate. A list would be easier. DEMO

Map

$icons: (
  users: '../../assets/files/images/admin/[email protected]',
  cms: '../../assets/files/images/admin/[email protected]',
  rules: '../../assets/files/images/admin/[email protected]',
  data: '../../assets/files/images/admin/[email protected],',
  setting: '../../assets/files/images/admin/[email protected]',
  logout: '../../assets/files/images/admin/[email protected]'
);

@each $key, $val in $icons {
  .#{$key} {
    background-image: url($val);
  }
}

List

$icon-list: users, cms, rules, data, setting, logout;

@each $key in $icon-list {
  ##{$key} {
    background-image: url('../../assets/files/images/admin/navicon_#{$key}[email protected]');
  }
}

Upvotes: 1

Related Questions