Martin Verdejo Martin Verdejo - 3 years ago 177
Sass (Sass) Question

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/navicon_users_unselected@2x.png',
cms: '../../assets/files/images/admin/navicon_content_unselected@2x.png',
rules: '../../assets/files/images/admin/navicon_rules_unselected@2x.png',
data: '../../assets/files/images/admin/navicon_data_unselected@2x.png,',
setting: '../../assets/files/images/admin/navicon_settings_unselected@2x.png',
logout: '../../assets/files/images/admin/navicon_logout_unselected@2x.png'
);


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
.

Ari Ari
Answer Source

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/navicon_users_unselected@2x.png',
  cms: '../../assets/files/images/admin/navicon_content_unselected@2x.png',
  rules: '../../assets/files/images/admin/navicon_rules_unselected@2x.png',
  data: '../../assets/files/images/admin/navicon_data_unselected@2x.png,',
  setting: '../../assets/files/images/admin/navicon_settings_unselected@2x.png',
  logout: '../../assets/files/images/admin/navicon_logout_unselected@2x.png'
);

@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}_unselected@2x.png');
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download