After spending some time working on a customized dropdown
with the use of CSS and Vanilla JavaScript (Plain JS), I encountered an issue while trying to select and update the dropdown text upon clicking an option:
window.onload = () => {
let [...options] = document.querySelectorAll('#select .opt');
let select = document.getElementById('select');
select.addEventListener('click', () => {
options.forEach(opt => {
opt.classList.toggle('showOpt');
});
});
options.forEach(opt => {
opt.addEventListener('click', event => {
let optArr = select.innerText.split('\n');
optArr[0] = opt.innerText;
select.innerText = optArr.join('\n');
});
});
}
#select {
border: none;
width: 100px;
padding: 5px;
}
.fas {
float: right;
}
.opt {
list-style: none;
display: none;
margin: 3px;
padding: 4px;
border-bottom: 1px solid green;
}
.opt:hover {
background: white;
}
.showOpt {
display: block !important;
}
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet"/>
<button id='select'>
Level 1<i class="fas fa-chevron-down"></i><br/>
<li class='opt' value='1'>Level 1</li>
<li class='opt' value='2'>Level 2</li>
<li class='opt' value='3'>Level 3</li>
<li class='opt' value='4'>Level 4</li>
</button>
Here is a pen of the above code.
If we consider that the user has selected the Level 3 option,
I am now faced with the question - how do I successfully update the dropdown text (initially set as Level 1) usingJavaScript / ES6
?
Despite my attempts to utilize the element.innerText
function of JavaScript, unfortunately, it did not yield the desired outcome!