I have the following button element in my HTML
<button id="play-pause" aria-hidden="true"></button>
On the jQuery ready event, I run the following code:
$('#play-pause').attr('data-icon', '')
That turns the HTML element into this
<button id="play-pause" aria-hidden="true" data-icon=""></button>
Which renders like this in the browser (Chrome stable):
However, if I delete the JavaScript code, manually change the HTML to the following (it's the same thing as the JS waas doing) and refresh the page:
<button id="play-pause" aria-hidden="true" data-icon=""></button>
then it renders like this:
What's the difference?
I suspect it's irrelevant but here's the CSS:
/* Use the following CSS code if you want to use data attributes for inserting your icons */
[data-icon]:before {
font-family: '45sound';
content: attr(data-icon);
speak: none;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
font-style:normal;
}
There are 2 ways to set the data attribute of an element using Javascript. The way I typically set the data attribute is with the dataset property, and the other way is using the setAttribute () method. To set the data attribute with the dataset property do the following: Using the dataset property of that element, set the data attribute.
With data- attributes, we can store data that we want to store within our HTML elements. And we can use JavaScript to do this. In this article, we’ll look at how to get and set the value of the data-id attribute of an element with JavaScript. One way to get the value of an attribute is to use the getAttribute method available natively.
To insert an icon, add the name of the icon class to any inline HTML element. The <i> and <span> elements are widely used to add icons.
Read, write, or remove data values of an element. In vanilla JavaScript setting a data attribute of an element is done with the generic setAttribute () method. This is the equivalent of jQuery's $.data () method.
Use Unicode value:
$('#play-pause').attr('data-icon', '\uE00A');
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