0

I have a script on a page referencing a function in an external script (it converts a Markdown file to HTML and displays it as the innerHTML of a div):

$(document).ready(function() {

  let input = document.getElementById('input');
  let output = document.getElementById('output');
           
  $("#input").load("convertme.md", function() {
    output.innerHTML = convert(input.innerText);
  });
});

with:

<div id="input" style="display: none;"></div>
<div id="output"></div>

This way, convert() works fine, the original markups become proper HTML tags. But I want to shorten the code, by merging the two div into one, say <div id="content"></div>, as the only innerText area to be handled by the function (so that I wouldn't have to hide the pre-conversion text). I changed the function to:

$(document).ready(function() {

  let content = document.getElementById('content');

  $("#content").load("convertme.md", function() {
    content.innerHTML = convert(content.innerText)
  });
});

This way, however, the conversion is imperfect: it fails to convert the Markdown paragraphs into p, such that all the paragraphs following each header become embedded inside <h1>...</h1> etc instead of <p>...</p>. Why?

Or is there a better way to merge the input and output div?

Miranda N
  • 65
  • 6
  • https://stackoverflow.com/questions/19030742/difference-between-innertext-innerhtml-and-value – GrafiCode Sep 02 '21 at 12:39
  • You could set up a demo with the first div already populated. Your question only involves what happens after. Use the snippet editor. – isherwood Sep 02 '21 at 12:46
  • There's no *obvious* reason in the code provided. Would need to see it in action ([mcve]) with the problem occurring. Perhaps your #content isn't just a simple div? – freedomn-m Sep 02 '21 at 12:53
  • Note that you don't need `convert(content.innerText)` but can do `$(..).load(url, function(html) { content.innerHTML = convert(html); })`. In which case you're not really using `.load` and should just use a `$.ajax` GET – freedomn-m Sep 02 '21 at 12:56
  • Note - `$("#input")` can be replaced with `$(input)` and ` $("#content")` can be replaced with ` $(content)`. Doing this will prevent unnecessary searches for these elements. – phuzi Sep 02 '21 at 13:06

0 Answers0