How to populate select-option dropdown from css

144 Views Asked by At

I'm trying to populate a dropdown menu (select-option) in html that retrieves the options from a css file. To do that, I defined a custom class for each option and I wrote the option label in the css file with a CUSTOM_CLASS::after{content: "";} statement.

For instance, here is the definition of an option of the dropdown:

<option class="OPTION1_LABEL"></option>

And here is the css:

.OPTION1_LABEL::after{content: "Option 1";}

.DROPDOWN_TITLE::after {
  content: "Select option from dropdown";
}

.OPTION1_LABEL::after {
  content: "Option 1";
}

.OPTION2_LABEL::after {
  content: "Option 2";
}

.OPTION3_LABEL::after {
  content: "Option 3";
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>


<div class="col">
  <span class="input-group-text DROPDOWN_TITLE"></span>
</div>
<div class="col">
  <select class="form-control" id="myDropdown">
    <option class="OPTION1_LABEL"></option>
    <option class="OPTION2_LABEL"></option>
    <option class="OPTION3_LABEL"></option>
  </select>
</div>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

https://jsfiddle.net/fm623k48/

However, the dropdown menu doesn't get populated. How can I solve?

1

There are 1 best solutions below

0
la_petite_kozel On

Select is a control element and browsers mostly ignore :before and :after for control elements and their children. So most likely it's not possible. In case you can't edit your HTML you can try to populate select using JS.

Alternatively if you really need to populate select using CSS pseudo content you can try using getComputedStyle() method, but it's also JS