document.querySelector('.custom-select-wrapper').addEventListener('click', function() {
this.querySelector('.custom-select').classList.toggle('open');
})
for (const option of document.querySelectorAll(".custom-option")) {
option.addEventListener('click', function() {
if (!this.classList.contains('selected')) {
this.parentNode.querySelector('.custom-option.selected').classList.remove('selected');
this.classList.add('selected');
this.closest('.custom-select').querySelector('.custom-select__trigger span').textContent = this.textContent;
this.parentElement.previousElementSibling.style.backgroundImage = getComputedStyle(this).backgroundImage;
}
})
}
window.addEventListener('click', function(e) {
const select = document.querySelector('.custom-select');
if (!select.contains(e.target)) {
select.classList.remove('open');
}
});
Переписал ваш код на более рациональный:
const select = document.querySelector('.custom-select');
(function() {
let input = select.firstElementChild,
text = input.querySelector('span'),
options = select.lastElementChild;
select.addEventListener('click', function(ev) {
this.classList.toggle('open');
let el = ev.target;
if (el.classList.contains('custom-option')) {
options.querySelector('.selected').classList.remove('selected');
el.classList.toggle('selected');
text.textContent = el.textContent;
input.style.backgroundImage = getComputedStyle(el).backgroundImage;
}
});
})();
window.addEventListener('click', function(e) {
if (!select.contains(e.target)) {
select.classList.remove('open');
}
});