简体   繁体   中英

HTML/JS - Unable to Render HTML while Converting from Markdown

In this example I'm trying to convert everything in #fileDisplayArea to markdown. However, the raw HTML within the div is not applied.

    <div id="fileDisplayArea"># Title
    Lorem **ipsum** dolor sit amet, *consectetur adipiscing* elit

    <center>Consectetur libero id faucibus nisl tincidunt eget</center>

    In ornare quam viverra orci sagittis eu.
    </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/10.0.0/markdown-it.min.js"></script>
        <script>
            let md = window.markdownit();
            let txt = document.getElementById('fileDisplayArea').innerHTML;
                document.getElementById('fileDisplayArea').innerHTML = md.render(txt);
        </script>

Running this code properly converts the markdown elements but the raw HTML is not read and instead shows up in the output. Changing the last instance of innerHTML to innerText provides the following output:

    <p>Lorem <strong>ipsum</strong> dolor sit amet, 
    <em>consectetur adipiscing</em> elit</p>
    <p>&lt;center&gt;Consectetur libero id faucibus nisl tincidunt eget&lt;/center&gt;</p>
    <p>In ornare quam viverra orci sagittis eu.</p>

This shows that the less/greater than symbols are being escaped. How do I prevent this?

You can either use textContent instead of innerText to skip HTML tags or enclose the node in backticks to show it as a code block, but innerText will always convert brackets. This happens because the library you're using watch for strings and you're trying to convert an HTML node. Also, there's no native way to center text with Markdown.

For anyone else who may stumble across this, I managed to find the solution. Within the documentation for markdown-it, certain options are disabled by default. Being able to implement raw HTML is disabled. To fix this, the html flag needs to be enabled. Replace:

    let md = window.markdownit();

with the following:

    let md = window.markdownit({ 
        html: true, 
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM