JSFiddle - React, Tailwind, and code Playground
by supertrue
HTML
<textarea id="content" rows="10" cols="20"><h1>This is an h1</h1>
<p>Bla bla bla bla bla bla</p>
<h2>This is an h2</h2>
<p>Bla bla bla bla bla bla</p>
<h3>This is an h3</h3>
<p>Bla bla bla bla bla bla</p>
</textarea>
<iframe id="iframe-toc"></iframe>
CSS
textarea {width: 200px; height= 200px;}
JavaScript
function myQuickTOC() {
var body = $('#content').val();
// var headers = $(body).filter('h1, h2, h3, h4, h5, h6');
var headers = $(body).filter(':header');
headers.each(function() {
$(this).wrap('<li class="' + this.nodeName.toLowerCase() + '">');
// alert('Header title: ' + $(this).html() );
});
// This returns just the first header, with no html:
// headers = headers.html();
// This returns just the last header, in its <h3> tag:
headers = headers.clone().wrap('<div>').parent().html();
// How do I return all of the headers?
// Like this: <li class="h1">This is an h1</li><li class="h2">This is an h2</li><li cl...
// alert(headers);
return headers;
}
var toc = myQuickTOC();
// alert('myQuickTOC() returns ' + toc);
$("#iframe-toc").contents().find("body").html('<h5>This should list all headers:</h5>' + toc);
//$("#div-toc").html('<h1>testtttttt</h1>' + toc22 );
$('#content').keyup(function() {
var $this = $(this);
var body = $("#iframe-toc").contents().find("body");
body.html( myQuickTOC() );
});