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?
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With