Open In App

How to declare a custom attribute in HTML ?

In this article, we will learn how to declare a custom attribute in HTML. Attributes are extra information that provides for the HTML elements. There are lots of predefined attributes in HTML.

When the predefined attributes do not make sense to store extra data, custom attributes allow users to create custom data. If you want to define your own custom attributes in HTML, you can implement them through the data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery. There are some rules to keep in mind before defining your custom attributes.



Any ordinary HTML element can become rather complex and custom defined through the HTML data-* attribute. Let us define a simple article tag in HTML for this article and store some extra information. You can access these values in JavaScript and CSS and use them according to your purpose. You can even define names similar to predefined tags. A custom attribute data-id is different from the id tag that is usually used. You can console the values and test that out.

Example: In this example, we will declare a custom attribute.






<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            background-color: "red";
        }
        article[data-parent="GFG"] {
            width: 1000px;
            font-size: 50px;
            color: green;
        }
        article[data-parent="GFG2"] {
            width: 600px;
            color: black;
            font-size: 50px;
        }
    </style>
</head>
<body>
    <article id="1"
        data-title="custom-attributes"
        data-parent="GFG">
        Sample GFG article on Custom Attributes.
    </article>
 
    <article id="2"
        data-title="custom-attributes-2"
        data-parent="GFG2">
        Sample GFG second article
        on Custom Attributes.
    </article>
    <script>
        const article = document.getElementById('1');
        const article2 = document.getElementById('2');
        // "custom-attributes"
        console.log(article.dataset.title);
        // "GFG"
        console.log(article.dataset.parent);
                    // "custom-attributes-2"
        console.log(article2.dataset.title);
                // "GFG2"
        console.log(article2.dataset.parent);
    </script>
</body>
</html>

Output:

custom attributes


Article Tags :