If I do the following:
$('.js-element').attr("data-count", 2)
then I can show that value using CSS as:
.js-element:after {
content: attr(data-count);
}
But if I do the following:
$('.js-element').data("count", 2)
then the same CSS code shows nothing.
As I understanding the difference is that in the first case I am just setting an attribute on the HTML element that I happen to prefix with data, while in the second case I am setting the dataset property of HTML element.
My questions are:
Getting a data attribute's value in CSS # You can access the content of a data attribute with the attr() CSS function. In every major browser, it's use is limited to the content property. For example, let's say you wanted to add some content dynamically to a component based on a data attribute value. You could do this.
To use this selector, add a pipe character (|) before the equals sign. For example, li[data-years|="1900"] will select list items with a data-years value of “1900-2000”, but not the list item with a data-years value of “1800-1900”. Value ends with: attribute value ends with the selected term.
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
Data-Attributes in CSS Data-attributes can be read in CSS using the content property. The content CSS property can be used only on ::before and ::after pseudo-elements. <div id="container" data-point="14">Post 1</div>
In the above example whenever value of data-point changes, the rendered content of #container::before will be changed to the new value of the attribute. You can also set specific CSS properties when the value of the data-attribute equals a specific value.
We can store extra information about elements using data-* attribute. The following examples illustrate CSS data-* attribute.
Whenever content in a page changes, the usual process is to show the changed content through Javascript (appening new HTML). But this can be alternatively done by using data-attributes in CSS — whenever value of data-attribute changes, the new value is rendered automatically in the page.
As I understanding the difference is that in the first case I am just setting an attribute on the HTML element that I happen to prefix with data
Yes
while in the second case I am setting the dataset property of HTML element.
No. You are setting jQuery's internal data store.
Can one of the methods be considered better than the other?
That's subjective
How can I get CSS to show values from the dataset?
Set the dataset value (document.querySelector('.js-element').dataset.count = 2
), which will map onto the attribute automatically.
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