JSFiddle - React, Tailwind, and code Playground

by moob

HTML

<select data-selected="3">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>
<select data-selected="0">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option value="0">4</option>
</select>

JavaScript

//return all elements with matching attribute
function getAllElementsWithAttribute(attr,el){
    var matchingElements = [];
    var tagname = el || '*'
    var allElements = document.getElementsByTagName(tagname);
    for (var i = 0; i < allElements.length; i++){
        if (allElements[i].getAttribute(attr)){//if element exists with attribute.
            matchingElements.push(allElements[i]);
        }
    }
    return matchingElements;
};
//preselect options equal to the select's data-selected attr
function preSelect(){
    var selects = getAllElementsWithAttribute('data-selected','select');
    for (var i = 0; i < selects.length; i++){
        var zis = selects[i];
        var selectIfValueEquals = zis.getAttribute('data-selected');
        if(selectIfValueEquals){
            var opts = zis.options;
            for (var x = 0; x < opts.length; x++){
                var o = opts[x];            
                if (o.value == selectIfValueEquals){
                    o.selected = true;
                    break;
                }
            } 
        }
    }
};
window.onload = function () {
    preSelect();
}