Replace button elements with option elements in a select dropdown on smaller viewports

A horizontal row of buttons (or links) looks great on large viewports but there’s no space for that on small (mobile) viewports. We could use CSS to simply stack the buttons but then it takes up too much vertical screen real estate.

Instead we can use Javascript to take the button elements and use them to build a new select element with corresponding option elements. This effectively turns the row of buttons into a dropdown menu which is much easier to use on a mobile device.



const replaceButtons = () => {
	const parent = document.querySelector('.nav-buttons');
	const ulElement = parent.querySelector('ul');

	const selectElement = document.createElement('select');
	if (ulElement) {
		ulElement.querySelectorAll('li').forEach(li => {
			const buttonElement = li.querySelector('button');
			const optionElement = document.createElement('option');

			optionElement.setAttribute('data-tab-id', buttonElement.getAttribute('data-tab-id'));
			optionElement.setAttribute('class', buttonElement.getAttribute('class'));

			optionElement.textContent = buttonElement.textContent;



<div class="nav-buttons">
		<li><button data-tab-id="1" class="button__item button__item--active">Button A</button></li>
		<li><button data-tab-id="2" class="button__item">Button B</button></li>
		<li><button data-tab-id="3" class="button__item">Button C</button></li>
		<li><button data-tab-id="4" class="button__item">Button D</button></li>
		<li><button data-tab-id="5" class="button__item">Button E</button></li>
		<li><button data-tab-id="6" class="button__item">Button F</button></li>
		<li><button data-tab-id="7" class="button__item">Button G</button></li>


.nav-buttons {
	ul {
		display: flex;
		gap: 1em;
		justify-content: center;
		list-style: none;
		margin: 0;
		padding: 0;
	button {
		padding: 1.5em 2em;
	select {
		display: none;
		margin-inline: auto;
		padding: 1.5em;
	select {
		background-color: #ebebeb;
		border: 1px solid #636363;
	@media (max-width: 1024px) {
		ul {
			display: none;
		select {
			display: block;