Open In App

How To Set Custom Attribute Using JavaScript?

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In modern web development manipulating HTML elements dynamically is a common requirement. One such task is setting custom attributes on elements to store additional data or metadata.

Custom attributes referred to as data attributes allow developers to attach extra information to elements. In this article, we will see various methods to set custom attributes using JavaScript.

Why use Custom Attribute?

Custom Attributes are useful because they allow you to store information directly in your HTML elements. You can easily access and change these attributes using JavaScript.They can help manage dynamic changes on your web pages, like tracking a user's actions.

Prerequisites

These are the approaches to set custom attributes using JavaScript:

1. Using the setAttribute() method

In this approach, we will use the setAttribute() method which is a simple way to set any attribute including custom attributes, on an HTML element. This method allows us to specify the attribute name and value as strings.

Syntax:

element.setAttribute('data-custom-attribute', 'value');

Example: In this example we are using the setAttribute() method to set custom attribute using JavaScript and then retire its value.

JavaScript
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
     content="width=device-width,
      initial-scale=1.0">
    <title>Set Custom Attribute</title>
</head>

<body>
    <div id="myElement">Welcome to GeeksForGeeks!</div>
    <script>
        const element =
        document.getElementById('myElement');
        element.setAttribute('data-info', 'customValue');
        console.log(element.getAttribute('data-info'));
    </script>
</body>

</html>


Output:

Open console to see output

customValue

2. Using element.attributeName syntax

We can also set custom attributes by directly assigning values to the attribute name using dot notation. However, this approach is less common and is typically used for standard attributes rather than custom ones.

Syntax:

element.customAttribute = 'value';

Example: In this example we are using element.attributeName syntax to set custom attribute using JavaScript.

JavaScript
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
     content="width=device-width,
      initial-scale=1.0">
    <title>Set Custom Attribute</title>
</head>

<body>
    <div id="myElement">
        Welcome to GeeksForGeeks!</div>
    <script>
        const element =
         document.getElementById('myElement');
        element.dataInfo = 'customValue';
        console.log(element.dataInfo);
    </script>
</body>

</html>


Output:

Open console to see output

customValue

Next Article
Article Tags :

Similar Reads