Open In App
Related Articles

How to declare a custom attribute in HTML ?

Like Article
Save Article
Report issue

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.

  • You must define your attribute in lowercase letters. Even though some browsers do automatically correct mistakes in the markup, it can cause errors, and they are not valid HTML5.
  • It must not start with XML (case-insensitive)
  • It should not contain any colon characters ( : ).

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>
        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;
    <article id="1"
        Sample GFG article on Custom Attributes.
    <article id="2"
        Sample GFG second article
        on Custom Attributes.
        const article = document.getElementById('1');
        const article2 = document.getElementById('2');
        // "custom-attributes"
        // "GFG"
                    // "custom-attributes-2"
                // "GFG2"



custom attributes

Last Updated : 09 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads