html – How to replace selection with Mathjax Javascript?

Link to fiddle

I would like to create a button that replaces the selected text with a rendered Mathjax equation.

For HTML, I have:


     <script type="text/x-mathjax-config">
  extensions: ["tex2jax.js"],
  tex2jax: {inlineMath: [["$","$"]]}
<script type="text/javascript" async src=

     <button id="math" type="button">Math</button>
     <button id="italic" type="button">Italic</button>
     <button id="bold" type="button">Bold</button>

     <div id="editor" contenteditable="true" spellcheck="false">
       <p>press the button to display math like this: $a + b = c$</p>


And for JavaScript, I have:

$('#math').click(function() {
  const selection = window.getSelection();
  const body = document.body;
  p = document.createElement('p');
  const math = "$x + y$";
  p.innerHTML = math;
  body.innerHTML = body.innerHTML.replace(selection, p);
    MathJax.Hub.Queue(["Typeset", MathJax.Hub, p]);

$('#italic').click(function() {
  document.execCommand("italic", false, null);

$('#bold').click(function() {
  document.execCommand("bold", false, null);

I am not getting the desired behavior. For example, if I select the first word, “press,” and click the Math button, the output is

enter image description here

What I want is to change the selected text to an arbitrary TeX equation.


Read more here: Source link