Converting Unordered List to Select Dropdown with jQuery
You have an unordered list (UL) formatted as follows:
<ul class="selectdropdown"> <li><a href="one.html" target="_blank">one</a></li> <li><a href="two.html" target="_blank">two</a></li> <li><a href="three.html" target="_blank">three</a></li> <li><a href="four.html" target="_blank">four</a></li> <li><a href="five.html" target="_blank">five</a></li> <li><a href="six.html" target="_blank">six</a></li> <li><a href="seven.html" target="_blank">seven</a></li> </ul>
Your goal is to convert it into a dropdown (
<select> <option value="one.html" target="_blank">one</option> <option value="two.html" target="_blank">two</option> <option value="three.html" target="_blank">three</option> <option value="four.html" target="_blank">four</option> <option value="five.html" target="_blank">five</option> <option value="six.html" target="_blank">six</option> <option value="seven.html" target="_blank">seven</option> </select>
jQuery Solution:
To achieve this conversion, you can use the following jQuery code:
$(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); }); });
Explanation:
This code will effectively convert your unordered list into a nicely styled select dropdown.
The above is the detailed content of How can I convert an unordered list to a select dropdown using jQuery?. For more information, please follow other related articles on the PHP Chinese website!