<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js" integrity="sha512-SYfDUYPg5xspsG6OOpXU366G8SZsdHOhqk/icdrYJ2E/WKZxPxze7d2HD3AyXpT7U22PZ5y74xRpqZ6A2bJ+kQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
window.onload = function() {
var md = window.markdownit();
var div = document.getElementsByClassName('markdown');
for(var i = 0; i < div.length; i++) {
var content = div[i].innerHTML;
document.getElementsByClassName('markdown')[i].innerHTML = md.render(content);
}
}
</script>
</head>
<body>
<div class="markdown">
# h1 Heading
## h2 Heading
### h3 Heading
#### h4 Heading
##### h5 Heading
###### h6 Heading
+ one
+ two
+ two and half
+ three
+ three and half
+ three point seventy five
</div>
</body>
</html>
This is an example of how to call markdownit() for a specific div after the page loads.
On my page, div tags are loaded dynamically after certain user actions. How do I call markdownit() for an emerging div with the id="markdown" attribute?
2
Answers
You can reuse your
md
object and callrender
on the content you wish and pass the result to theinnerHTML
of the div you create. Here’s an example, where after page load, 100 milliseconds later a newdiv
is created and the process is applied to it successfully.You can achieve this by simply moving your code into a separate function, then call that function whenever user submit new content.
Example: