Changing icon font data attribute with jQuery

Icon Fonts are all the rage I guess, but they’re a little tricky to deal with when it comes to replacing one of them. Since they rely on data- element to display the icon, if you need to do any changes (such as changing an up arrow to a down arrow) you might run into a fun little issue.

Assuming you’re encoding your site in utf8 with a header tag, that data-icon tag will probably show up as a blank box character, since it’s not something that utf8 wants to agree with. Typically you just use the html special character code, such as ⇝ to display an icon font.

The problem shows up when you try and make a change to the data-icon with jQuery. If you simply try and set the $(‘#element’).attr(‘icon’,’⇝’), this breaks. The problem is that jquery passes the string in encoded in utf8, not the html entity that the data-icon element is looking to access.

To fix, you need to get the html decoded value for the html entity before setting the data-icon from jquery.

In order to get the decoded value, you can use something like this

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes[0].nodeValue;
}

Leave a Reply

Your email address will not be published. Required fields are marked *