How to convert unordered list into nicely styled dropdown using jquery?

$(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);
    });
});

EDIT

As with any jQuery code you want to run on page load, you have to wrap it inside $(document).ready(function() { ... }); block, or inside it’s shorter version $(function() { ... });. I updated the function to show this.

EDIT

There was a bug in my code also, tried to take href from the li element.

Leave a Comment