Search code examples
jquerycssmaterialize

MaterializeCSS Change Option Color for Some Options


I am using a select dropdown from MaterializeCSS. I want to create a class that will change the text color of some options. Is there a way to do that?

I saw that I can change the color in general by doing:

.dropdown-content li>a, .dropdown-content li>span {
    color: red;
}

but this will affect all dropdown colors to be red. Is there a way to specify a class that can alter the text color for only some options.

I was looking to have something like the following:

<option value='A'>A</option>
<option value='B' class='red'>B</option>
<option value='C'>C</option>

Solution

  • You cannot change the behaviour of materializecss' javascript components from the html, since they are rewritten (the select you see is not the original one you provided in the html, since that one is hidden)

    To achieve what you have requested i have used a simple loop over the new "option" elements just after the initzialization. When it finds the one you want, it sets the class of the element to the materializecss' helper class materialize-red-text.

    document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('select');
        var instances = M.FormSelect.init(elems, {});
        changeColor();
    });
    
    function changeColor(){
      var options_elem = document.querySelectorAll(".dropdown-content li>a, .dropdown-content li>span");
      
      //index==0 is the disabled option element
      options_elem.forEach(function(element, index){
        if(index == "2") element.classList.add("materialize-red-text"); //or you could use class "redtext"
      });
    }
    .redtext {
        color: red !important;
    }
    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    
    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    
    <div class="input-field col s12">
      <select>
          <option value="" disabled selected>Choose your option</option>
          <option value="1">Option 1</option>
          <option value="2">Option 2</option>
          <option value="3">Option 3</option>
        </select>
      <label>Materialize Select</label>
    </div>