Home > Article > Web Front-end > How to Convert Unordered Lists to Stylish Select Dropdowns using jQuery?
Imagine having an unordered list filled with links and you want to transform it into a sleek select dropdown. With the power of jQuery, it's an easy task.
The following code snippet converts an unordered list with anchor tags linking to external pages into a select dropdown:
$(function() { $('ul.selectdropdown').each(function() { var $select = $('<select />'); $(this).find('a').each(function() { var $option = $('<option />'); $option.attr('value', $(this).attr('href')).html($(this).html()); $select.append($option); }); $(this).replaceWith($select); }); });
This code iterates over each unordered list with the class "selectdropdown," creates a select element for each list, adds an option for each link within the list, and replaces the original list with the select element.
To style the select dropdown, you can refer to external styling libraries like jQuery Transform. Additionally, you can modify the code to automatically open the selected link in a new window or tab:
$(function() { $('ul.selectdropdown').each(function() { var $select = $('<select />'); $(this).find('a').each(function() { var $option = $('<option />'); $option.attr('value', $(this).attr('href')).html($(this).html()); $select.append($option); }); $(this).replaceWith($select); - $select.on('change', function() { window.open($(this).val(), '_blank'); }); + $select.on('change', function() { window.open($(this).find('option:selected').val(), '_blank'); }); }); });
This modification adds an event listener to the select element that opens the selected link in a new window or tab when the user changes the value of the select element.
With these enhancements, you can easily create stylish and functional select dropdowns from unordered lists using jQuery.
The above is the detailed content of How to Convert Unordered Lists to Stylish Select Dropdowns using jQuery?. For more information, please follow other related articles on the PHP Chinese website!