optgroup with options to ul with li

Viewed 468

I'm making a custom select dropdown. I'm trying to convert the options to li elements which works so far. For the conversion I simply use $(selector).each(..). But I want, if they exist inside the select element, convert the opgroups to ul elements and place their options inside of them as li elements.

So to brake it down
If I have:
<select>
<option>
<option>
<option>
</select>
or
<select>
<optgroup>
<option>
<option>
<option>
</optgroup>
</select>

Should become:
<li>
<li>
<li>
or
<ul>
<li>
<li>
<li>
</ul>

How can I achieve this in jQuery? Like I want to have the optgroups as ul only if they are in the select. And the options in the right ul based on their optgroup. My problem right now is that I get all the options in every optgroup (so the same options in every optgroup which is NOT what I want).

*The optgroup should become the ul to which the appropriate options must be appended as li elements.

2 Answers

With jQuery each method you could do something like this:

  <select>
    <option value="">Test 1</option>
    <option value="">Test 2</option>
    <option value="">Test 3</option>
  </select>

  <ul></ul>

  <script>

    $(document).ready(function() {
      

      $('select option').each(function() {

        var li = '<li>' + $(this).text() + '</li>';
        $('ul').append(li);

      });


    })

  </script>

You can check if the current element which is refer inside each loop is OPTGROUP using prop("tagName") if yes use each loop to loop through option tags inside that and append generated html .

Demo Code :

var html = "";
$("select > * ").each(function() {
  //check tag name
  if ($(this).prop("tagName") == "OPTGROUP") {
    html += "<ul>" //create ul append it
    //loop throuh options
    $(this).find("option").each(function() {
      html += "<li>" + $(this).text() + "</li>" //append li
    })
    html += "</ul>" //close ul tag
  } else {
    html += "<li>" + $(this).text() + "</li>" //if option is there
  }
})
$("#result").html(html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option> S </option>
  <optgroup label="First">
    <option> A </option>
    <option> B </option>
  </optgroup>
  <optgroup label="Second">
    <option> E </option>
    <option> F </option>
  </optgroup>
  <option> R </option>

</select>


<ul id="result"></ul>

Related