How to Create a Custom Attribute for an HTML Element

HTML


In this article, we show how to create a custom attribute for an HTML element.

By custom attribute, we mean you can add any type of attribute to any given HTML element.

If you are just creating a static web page that has nothing other than HTML and CSS, then adding custom attributes to HTML elements is generally not needed and is not necessary.

However, when you begin working with Javascript and AJAX, along with a server-side language, then adding custom attributes to HTML elements can be crucial for a fully-functioning website.

Adding custom attributes to HTML elements allows you to pass more information about an HTML element, such as maybe the id of the HTML element, the title of the HTML element, the author of an HTML element (such as who wrote a paragraph), along with any other type of metadata needed about a particular section of a website.

Again, when you begin working with technologies such as Javascript and AJAX, this becomes crucial in order to pass information from the server-side code to AJAX.

For example, let's say you are creating a webpage that has comments from users. Let's say you are creating the website in Python, for example, and you have a for loop within a certain portion of the code that contains crucial comment information, such as the author of the comment, the date the comment was written, etc. Because the for loop is restricted to this portion of the website and the AJAX code is normally at the top and bottom of the website, you may not be able to access this information. However, you can if you add the information needed as custom attributes to the HTML elements.

So how do we add custom attributes to HTML elements?

We can create any custom attribute, by adding, data-, followed by the attribute name.

Let's say, for example, we want to have a custom author attribute, which represents the author of a paragraph.

We can do this with the following code shown below.



Within the full HTML element, this would look like the following.



Now since the data is in this attribute, data-author, we can easily access this data anywhere on the web page through Javascript or jQuery, by using the following line, var author= $('#paragraph1').attr('data-author');

Let's say we want to add another custom attribute. Again, we use, data-, followed by the custom attribute name.

Below is a paragraph tag with two custom attributes, data-author and data-date.



So this is how you can add custom attributes to HTML elements.

For complex websites, this is a very important concept, because with Javascript, we can fetch any attribute from an HTML element anywhere on the page.

And this is how to add a custom attribute to an HTML element.

HTML Comment Box is loading comments...