Transforming a jquery answer to vanilla js, you need sth like this
function changeWidth() {
let ghostSelect = document.createElement('select');
const select = document.getElementById('select');
var x = select.options[select.selectedIndex].text;
const ghostOption = document.createElement("option");
ghostOption.setAttribute("value", x);
var t = document.createTextNode(x);
ghostOption.appendChild(t);
ghostSelect.appendChild(ghostOption);
window.document.body.appendChild(ghostSelect)
select.style.width = ghostSelect.offsetWidth + 'px';
window.document.body.removeChild(ghostSelect)
}
<select id="select" onChange="changeWidth()">
<option value="all">Choose one</option>
<option value="1">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</option>
<option value="2">bbbbbbbbbbbbbbb</option>
<option value="3">cccc</option>
<option value="4">ddd</option>
<option value="5">ee</option>
<option value="6">f</option>
</select>
So what it actually does is that it creates a dummy select with only the selected option, adds it temporarily to the DOM, then calculates the width, sets the original's select
width to the new width and then it removes the dummy select
from the DOM.