Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a custom attribute on a div?

Tags:

html

jquery

css

I need to get a number value in jQuery, but for this to work I need a 3rd attribute on my div.

<div class="button" id="button$post" numberlk="$total">

This works fine! But HTML the validator tells me:

Error: Attribute numberlk not allowed on element div at this point.

What can I do to make it work correctly?

like image 308
RGS Avatar asked Sep 17 '15 19:09

RGS


People also ask

Can div have data attribute?

An <div> element can have any number of data-* attributes, each with their own name. Using data-* attributes reduces the need for requests to the server.

Can we use custom attributes?

Custom attributes are attributes that are not part of the standard HTML5 attributes but are explicitly created. They allow us to add our own information to HTML tags. These are not specific and can be used with all the HTML elements.

Can I use name attribute on div?

The name attribute is not part of the specification for DIV elements. name is, generally speaking, only valid on form elements. With all due respect, sir, it is adequate for illustrating the matter at hand.

Can you use custom HTML attributes?

You can add custom HTML attributes to pages and page elements, which are rendered on the HTML tag of the page element. For example, this is useful when working with third-party frameworks that render page elements differently based on certain attributes.


1 Answers

While it's possible to create your own attributes in your HTML, you shouldn't. This is because it renders your HTML invalid which can lead to unexpected issues with the UI and also any Javascript running on the page.

A much better approach to store custom metadata in an element is to use a data attribute instead, eg data-numberlk="$total"

<div class="button" id="button$post" data-numberlk="$total">

You can then retrieve this value in jQuery using the data() method:

var likes = $('.button').data('numberlk');

Or using plain JS:

var likes = document.querySelector('.button').dataset.numberlk;
like image 100
Rory McCrossan Avatar answered Sep 24 '22 06:09

Rory McCrossan