🏯 Using custom fields within JavaScript events

  


When developing web interfaces, we often need to associate additional information with a page element and retrieve it in response to an event. In this article, we'll look at how to add custom fields to DOM elements, how to use them in event handlers, and what standard HTML alternatives offer with the data-* attribute.

🔗 Do you like Techelopment? Check out the site for all the details!

Introduction

When working with JavaScript and DOM events, each DOM node is an object: this means that, in addition to existing properties, we can add new ones and retrieve them in the event handler. The following code is a practical example:


let myElement = document.getElementById("my-element");
myElement.customField_1 = "Hello";
myElement.customField_2 = "World!";
myElement.addEventListener('click', myElementListener);

function myElementListener(event){ 
  let customField_1 = event.currentTarget.customField_1; 
  let customField_2 = event.currentTarget.customField_2; 

  console.log(`${customField_1} ${customField_2}`);
}

How the code works

  1. Element selection
    let myElement = document.getElementById("my-element");
    We retrieve the DOM element with id="my-element".

  2. Adding custom fields
    myElement.customField_1 = "Hello";
    myElement.customField_2 = "World!";
    
    Here, two new properties are added directly to the HTMLElement object. In JavaScript, objects are dynamic, so we can extend them at any time.

  3. Registering an event listener
    myElement.addEventListener('click', myElementListener);
    
    When the element is clicked, the myElementListener function will be executed.

  4. Retrieving custom fields within the listener
    let customField_1 = event.currentTarget.customField_1;
    let customField_2 = event.currentTarget.customField_2;
    
    event.currentTarget refers to the element to which the event listener is associated. This allows us to access the custom properties set previously.

  5. Output
    When the element is pressed:
    Hello World!
    will be printed to the console.

When it can be useful

  • Pass custom data to an event handler without resorting to global variables.
  • Associate additional runtime-calculated information with an element.
  • Keep data and behavior linked in the same DOM object.

Good practices

Although it works, this technique is not always the most recommended for long-term projects:

  • It can cause confusion with other native properties of the object.
  • It is not standardized in its names and risks conflicts with external libraries.

Recommended alternative: Use HTML data attributes.

Example:

<div data-custom-field-1="Hello" data-custom-field-2="World" id="my-element"></div>

and in JavaScript:

let myElement = document.getElementById("my-element");
let field1 = myElement.dataset.customField1;
let field2 = myElement.dataset.customField2;

Data attributes and dynamic data

Furthermore, the data-* attributes work great with dynamic values, because you can read and modify them via JavaScript the same way you modify any other element property.

Example with dynamic values

let myElement = document.getElementById("my-element");

// Set dynamic values
myElement.dataset.customField1 = "Hello";
myElement.dataset.customField2 = "World";

// Event listener
myElement.addEventListener("click", (event) => {
  let field1 = event.currentTarget.dataset.customField1;
  let field2 = event.currentTarget.dataset.customField2;
  console.log(`${field1} ${field2}`);
});

Why it can be better than custom properties

  1. Compatibility and readability
    All developers are familiar with data-*, so the code is more straightforward for readers.

  2. Persistence
    If the DOM is serialized (for example, in outerHTML), the data-* remains in the HTML tags, while dynamically added properties do not.

  3. CSS and selectors
    You can also select elements in CSS based on data-*:
    [data-custom-field-1="Hello"] {
      color: red;
    }
    
  4. No risk of overwriting native properties
    There's no risk of accidentally calling a property already defined by the HTML/DOM API.

💡 When to choose custom properties (as seen at the beginning of the article)

  • When the data is purely temporary and doesn't need to be visible or exported to HTML.
  • When you want to avoid "dirtying" the markup with attributes.

💡 When to choose data-*

  • When the data needs to be accessible to both JavaScript and markup (and perhaps even CSS).
  • When you want the values to survive DOM serialization operations.
  • When readability for other developers is needed.

Conclusion

Adding custom fields directly on DOM elements is possible and can be convenient in rapid or prototyping scenarios.

However, for more complex code Maintainable and readable, it's best to prefer standard approaches like data-* attributes.

Knowing both techniques allows you to choose the best approach for each situation.



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment