Casper Thule Hansen
Casper Thule Hansen

Reputation: 1550

Check if css class exist and can be applied

I am using lipis flag icon set, and angularjs. I want to check whether a given flag exist is the css. What is the best approach to this?

Right now I am just applying the class and if the flag does not exist, then nothing is shown.

 <i class="flag-icon" ng-class="'flag-icon-' + dialog.model.item.code | lowercase"></i>

I would however like to show some text like "No flag" if the class does not exist in css. To do this I need some way to check whether the given flag-icon-xx exists or not, but how do I do this?

Upvotes: 4

Views: 1640

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

Pure CSS Solution for Font-Based Icons

Edit: Looks like the icon set you're using is background-based, so please see the second part of my answer for a potential solution. I'll keep this part here for future readers.

If you're using a font-based icon set you can do this with pure CSS relatively easily. Simply have a base selector which applies the text "No flag" to either the ::before or ::after pseudo-element (depending on which the font-based icon set uses itself):

.flag-icon::before {
    content: 'No flag';
}

As long as our other font-based icons are declared after this declaration or have higher specificity, their own content property will override this.

Example

.flag-icon::before {
  content: 'No flag';
}

.flag-icon-star::before {
  content: '★'
}
<h3>Working Icon</h3>
<i class="flag-icon flag-icon-star"></i>

<h3>Default Text</h3>
<i class="flag-icon flag-icon-null"></i>

Pure CSS Solution for Image-Based Icons

If it isn't a font-based icon set you're using, you can still apply a similar approach to background-based icon sets. For this, we still the same ::before or ::after pseudo-element as we've used above, but override this completely on valid icon classes:

.flag-icon::before {
    content: 'No flag';
}

.flag-icon-1::before,
.flag-icon-2::before,
... {
    content: '';
}

Example

.flag-icon::before {
  content: 'No flag';
}

.flag-icon-star::before {
  content: '';
}

.flag-icon-star {  
  background: url(http://i.imgur.com/yiJrwe0.png) no-repeat;
  display: block;
  height: 131px;
  width: 100px;
}
<h3>Working Icon</h3>
<i class="flag-icon flag-icon-star"></i>

<h3>Default Text</h3>
<i class="flag-icon flag-icon-null"></i>

Upvotes: 6

Related Questions