JSFiddle - React, Tailwind, and code Playground

HTML

<select id="mySelect" multiple size="8">
    <option>A</option>
    <option>B</option>
    <option>C</option>
    <option>C</option>
    <option>D</option>
    <option>D</option>
    <option>E</option>
    <option>F</option>
</select>

JavaScript

$('#mySelect').on('change', function() {
    var $sel = $(this).find(':selected');
    if ($sel.length < 4) {
        $sel.addClass('selected');
        $(this).find(':not(:selected)').removeClass('selected');
    }else
        $(this)
        .find(':selected:not(.selected)')
        .prop('selected', false);
});