3

I have the opposite of what most are asking. I want to display the original Html character code instead of displaying its glyph.

I have a table of emojis using the latest Unicode codes. For example, 😀 😇 are written in the page as 😀 and &#1f607;. I am doing a quick reference utility, so that when I click one of them, I want to show the code of the graphic. Unfortunately, if I push the character value to an element's innerText or innerHTML, it always show the glyph. How do I display a value of &#1f600; in its literal form of &#1f600; and not 😀


Thanks for all the helpful answers. I tried using <code> and <pre> but they didn't work for me. I used jQuery to select a <code> element and set its text to &#x1f600;. The graphic is shown instead of the literal code characters. Perhaps I am using the wrong property or function. Or should I be not using jQuery at all?

My code is:

<script>
  $('.emoji').click( function() {
     $('#selected').text(this.innerText);
  });
</script>

<div class='emoji'>&#x1f600;</div> 
<div class='emoji'>&#x1f607;</div>

<code id='selected'></code>
JJJ
  • 32,902
  • 20
  • 89
  • 102
Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • 2
    Can the person downvoting all the answers please explain why? they all seem to work for me. It'd be helpful to explain what your issue is – Liam Nov 02 '16 at 11:28
  • 2
    Do you mean that you want to literally convert an existing character in the HTML to its character reference code, or are you asking how to display the values when you're building the table? All the answers so far are for the latter case, and none for the former. – JJJ Nov 02 '16 at 11:30
  • Please share your actual code, rather than just a description. – James Thorpe Nov 02 '16 at 11:37
  • I have updated my question with the code I used. – Old Geezer Nov 02 '16 at 11:41
  • Possible duplicate of [HTML-encoding in JavaScript/jQuery](http://stackoverflow.com/questions/1219860/html-encoding-in-javascript-jquery) – Pete Nov 02 '16 at 11:51

4 Answers4

5

You should be able to do something like:

&amp;#x1f600;

See this code pen

http://codepen.io/anon/pen/MbgKpw

Liam
  • 27,717
  • 28
  • 128
  • 190
Andrew Berry
  • 853
  • 3
  • 10
  • 25
4

The easiest way is to save the character code to a data attribute and pull it from there.

  $('.emoji').click( function() {
     $('#selected').text("&#x"+$(this).data('code')+";");
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='emoji' data-code="1f600">&#x1f600;</div> 
<div class='emoji' data-code="1f607">&#x1f607;</div>

<code id='selected'></code>
JJJ
  • 32,902
  • 20
  • 89
  • 102
1

In case you encode only the ampersand & and it will show what you want:

&amp;#x1f607;&#x1f607;

&#x1f607; 😇

user7103188
  • 148
  • 1
  • 12
-1

Here is a fiddle: https://jsfiddle.net/3mbdpzdq/

<xmp>
    &#x1f600;
</xmp>