<!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?
You can reuse your md
object and call render
on the content you wish and pass the result to the innerHTML
of the div you create. Here's an example, where after page load, 100 milliseconds later a new div
is created and the process is applied to it successfully.
<!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);
}
setTimeout(function() {
document.body.innerHTML += `
<div id="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>`;
document.getElementById("markdown").innerHTML = md.render(document.getElementById("markdown").innerHTML);
}, 100);
}
</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>