$(":header", div).each(function(i, el) { el = $(el); var title = el.text(); var id = ++i + "_toc"; var a = $("<a>",{id : id, text : title}); el.html(a); ToC += "<li><a href='#"+id+"'>" + title + "</a></li>" });