Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting element data-icon with JavaScript

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', '&#xe00a;')

That turns the HTML element into this

<button id="play-pause" aria-hidden="true" data-icon="&#xe00a;"></button>

Which renders like this in the browser (Chrome stable):

play pause button

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="&#xe00a;"></button>

then it renders like this:

play pause button rendered properly

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;
}
like image 334
David Tuite Avatar asked May 21 '13 23:05

David Tuite


People also ask

How to set the data attribute of an element using JavaScript?

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.

How to get the value of an element’s data-ID with JavaScript?

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.

How to insert an icon in HTML?

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.

How do I read and write data values of an element?

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.


1 Answers

Use Unicode value:

$('#play-pause').attr('data-icon', '\uE00A');
like image 153
Tomas Kirda Avatar answered Sep 28 '22 03:09

Tomas Kirda