Skip to content
Related Articles

Related Articles

Improve Article

How to declare a custom attribute in HTML ?

  • Last Updated : 22 Jul, 2021

Attributes are extra information that provide 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 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 lower case 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:

HTML




<!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

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :