How to access data attributes from event object

I updated your fiddle:

I was able to do it just by referencing with “getAttribute”

 event.target.getAttribute("data-sortorder");

this is with refs
https://jsfiddle.net/69z2wepo/46265/

 var sortOrder = this.refs.tester.getAttribute("data-sortorder");
 alert(sortOrder);//Should say "asc"
},
  render: function() {
    return <div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" ref="tester" onClick={this.handleClick}>Click Here Please</div>;
  }
});

Do this:-

  1. change your element, by adding a “ref” attribute.

    div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" ref="tester" onClick={this.handleClick}
    
  2. Then get that attribute like so: this.refs.tester.getAttribute("data-sortorder")

OR PER ORIGINAL REQUEST, w/o REFS:

  1. Or per “event specific” — it worked properly referencing it like so:
    event.target.getAttribute("data-sortorder");

NOTE: Now that we are 6yrs later, you can also use: (per niko9911 suggestion below)

event.target.dataset.sortorder

–> You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)