简体   繁体   中英

How do I get the custom attribute of an “option” tag after firing the “change” event listener?

My HTML:

<select>
    <option customAttr="foo">Foo Text</option>
    <option customAttr="bar">Bar Text</option>
</select>

My JS:

selectElement.addEventListener("change",function(){
    console.log(this.getAttribute("customAttr"));
});

This only logs null . Why? How do I make it log the value of customAttr ?

You have to target the selected option like the following:

 var selectElement = document.querySelector('select'); selectElement.addEventListener("change",function(){ var option = this.options[this.selectedIndex]; console.log(option.getAttribute("customAttr")); }); 
 <select> <option customAttr="foo">Foo Text</option> <option customAttr="bar">Bar Text</option> </select> 

You can also access to your attribute by adding a value in your option tag, like this :

 const select = document.getElementById('select'); select.addEventListener("change", (e) => { const options = select.querySelectorAll("option"); const item = e.target.value; console.log(options[item].getAttribute('customAttr')); }); 
  <select id='select'> <option value='0' customAttr="foo">Foo Text</option> <option value='1' customAttr="bar">Bar Text</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM