Sometimes, we want to get value from data attribute of selected dropdown with JavaScript.
In this article, we’ll look at how to get value from data attribute of selected dropdown with JavaScript.
How to get value from data attribute of selected dropdown with JavaScript?
To get value from data attribute of selected dropdown with JavaScript, we can get the selected option from the selectedOptions
property.
Then we get the data attribute value from the dataset
property.
For instance, we write:
<select>
<option data-fruit='apple'>apple</option>
<option data-fruit='grape'>grape</option>
<option data-fruit='grape'>grape</option>
</select>
to add a select drop down.
Then we write:
const select = document.querySelector('select')
select.onchange = (e) => {
const [option] = e.target.selectedOptions
console.log(option.dataset.fruit)
}
to select the select element with querySelector
.
Then we set the select.onchange
property to a function that gets the select option with e.target.selectedOptions
.
Then we get the data-fruit
attribute from the selected option element with dataset.fruit
.
Now we see the data-fruit
value logged when we pick an option.
Conclusion
To get value from data attribute of selected dropdown with JavaScript, we can get the selected option from the selectedOptions
property.
Then we get the data attribute value from the dataset
property.