I have seen in various HTML code such as: data-value, date-title, almost always are tag attribute names with the suffix: data-, I would like to know what they mean and without any use / advantage recommendation of use.
I have seen in various HTML code such as: data-value, date-title, almost always are tag attribute names with the suffix: data-, I would like to know what they mean and without any use / advantage recommendation of use.
Attributes are included from HTML5
.
Basically they are attributes used to assist the developer in dynamic queries on the page itself without having to access a servidor -> BD
.
The data could already be mounted on the page itself when requested to the server, and in case of any user interaction, are easily accessible via JavaScript
or CSS
.
The
data-*
attributes is used to store custom data private to the page or application.The
data-*
attributes gives us the ability to embed custom data attributes on allHTML
elements.The stored (custom) data can then be used in the page's
JavaScript
to create a more engaging user experience (without anyAjax
calls or server-sidedatabase
queries).
The
data-*
attributes are used to store custom data private to the page or application.The
data-*
attributes give us the ability to embed attributes of custom data on allHTML
elements.The stored data can then be used in
JavaScript
of the page to create a more user-friendly experience (without requiredAjax
calls or queriesBD
of server side).
Source: w3schools
$(".teste").click(function() {
pais = $(this).data("country");
if(pais =="Brasil") {
alert("Brasileiro!");
}else{
alert("Americano!");
}
});
.teste[data-country=Brasil] {
color: yellow;
background-color:green;
}
.teste[data-country=USA] {
color: red;
background-color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><liclass="teste" data-name="Marcelo Bonifazio" data-city="São Paulo" data-state="SP"
data-country="Brasil" data-lang="pt-br">
Clique-Aqui!
</li>
<li class="teste" data-name="Ricardo Henrique" data-city="Oklahoma City" data-state="Oklahoma" data-country="USA" data-lang="EN-en">
Clique-Aqui!
</li>
Very well explained by the friend @MarceloBonifazio.
However, only one correction: The example Javascript
would actually be done by the jQuery
library.
Without jQuery, the way to get this data from the data
attribute is done through the dataset
object, which comes "inside" the element that is selected by javascript.
See:
HTML:
<div data-nome="Stackoverflow" id="teste"></div>
Javascript:
var element = document.querySelector('#teste');
// obtém os dados
console.log(element.dataset.nome); // Stackoverflow
//define o dado
element.dataset.nome = 'SOPT';
In addition, the ways in which the data
attribute is treated are different, when we compare its usage between Javascript
pure and jQuery
This caused me confusion. My question was taken at this question I made here in SOPT.
See a small example of working code in JSFIDDLE