old-willow
old-willow

Reputation: 111

Select2 jQuery - How can I select a specific element in Select2 dropdown for changing arbitrary css property?

Basically, I only need to change one item's color in the dropdown when certain conditions are met so it can visually be different from others.

I can't find any specific way to select an element, because the id of the element is always changed whenever I reload the page, but there is a beginning and ending that is known. For example, this is one of the ids:

id="select2-id_category-result-8ejj-25"

The first fixed part is select2-id_category-result- and the second fixed part is -25, between varies. Other items in the list have different middle part and ending as their IDs.

If I construct the selector like this:

$('li[id^="select2-id_category-result"][id$="-25"]');

It never finds any element. What is the correct way to construct this kind of selector?

Upvotes: 1

Views: 1306

Answers (1)

Swati
Swati

Reputation: 28522

You can use select2-results__options class and .find() to change required li tag color . Also , you will only be able to change color of li tag when the option-box are open else it will not work because select2 generate that elements when you click on select element and by default they don't exist inside dom .

Demo Code :

$(function() {
  $(".select2").select2({
    "width": "100px"
  });
  var save_Reference = "";
  //wheen sleect is clicked
  $(document).on("click", ".select2", function() {
    //for further use if need id
    save_Reference = $(".select2-results__options").find("li[id$=-2]").attr("id")
    console.log(save_Reference)
    //or use it like this change 2 to 25
    $(".select2-results__options").find("li[id$=-2]").css("color", "red")

  })

})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>
<select class="select2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Upvotes: 1

Related Questions