How to access custom attributes from an event object

You can use following two approach to access attribute value from event object-

Approach 1 – Retrieve using standard Attribute: Here we can use name attribute. We access the attribute value using event.target.{attribute name}. Check printNameAttribute method in below code which retrieves value from Name attribute.

Approach 2 – Retrieve using Custom Attribute: Here we use data attribute. We access the attribute value using event.target.dataset.{data attribute name}. Check printDataAttribute method in below code which retrieves value from Data attribute. Data Attribute name is here target-id which is user defined. In javascript you will refer that as targetId.

<!DOCTYPE html>
<html>
 <body>
  <button data-target-id='This is Data Attribute Example' onclick="printDataAttribute(event)" >Test Data Attribute</button>
  <button name='This is Name Attribute Example' onclick="printNameAttribute(event)" >Test Name Attribute</button>
    <p id="demo"></p>
	<script>
	 function printDataAttribute(event) { 
	  document.getElementById("demo").innerHTML = event.target.dataset.targetId;
	 }
     function printNameAttribute(event) { 
	  document.getElementById("demo").innerHTML = event.target.name;
	 }
	</script>
 </body>
</html>

Note: The same way of retrieving value using event can be used in Lighting Web Component as well.

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply