PURE JS get selected option data attribute value returns Null

前端 未结 4 1183
星月不相逢
星月不相逢 2021-01-01 12:32

I have this html:


  
  
  
  

assuming you want the custom attribute to be "id".

There are two ways you can retrieve the value of "data" attributes using pure JavaScript: in addition to the good old fashion get/setAttribute(), you can also access using the "dataset" property of the element

Using DOM's getAttribute() property

function check_status(obj) {
      var myoption = obj.options[obj.selectedIndex];
      var uid = myoption.getAttribute('data');
      alert(uid);
      // setting and removing the data-id attribute
      myoption.setAttribute("data-id", "foo") //changes "data-id" to "foo"
      myoption.removeAttribute("data-id") //removes "data-id" attribute entirely
 }

Using JavaScript's dataset property

function check_status(obj) {
      var myoption = obj.options[obj.selectedIndex];
      var uid = myoption.dataset.id;
      alert(uid);
      var statusId = myoption.dataset["id"] 
      alert(statusId);
}

提交回复
热议问题