Skip to content

Instantly share code, notes, and snippets.

@Velrok
Created May 4, 2012 21:15
Show Gist options
  • Save Velrok/2597772 to your computer and use it in GitHub Desktop.
Save Velrok/2597772 to your computer and use it in GitHub Desktop.
a javascript file that analyses the header structure of an html page and creates an overview
// This requires jquery
var html_output;
/**
@param h1_element - the html element to search for sub headers
@param output_element - the html element to put the output into. Normally a div.
*/
function create_page_overview(h1_element, output_element) {
var h1 = $(h1_element);
var out = $(output_element);
var id = "0_";
h1.attr("id",id);
html_output = "<strong>";
html_output += h1.html();
html_output += "</strong>";
process_siblings(h1, 2, id);
out.html(html_output);
}
function process_siblings (header, level, before_id) {
if (level >= 7) {
// there are only headers up to lvl 6 (h6)
return;
};
var siblings = header.siblings("h"+level);
if(siblings.size() == 0){
// no siblings left for this level
return;
}
// when we reach this point of exection we have at least 1 sibling
// so we create a new list
html_output +="<ul>";
//console.log(siblings);
siblings.each(function (k, v) {
var k = $(k);
if(k.size() == 0){
k = 0;
} else {
k = parseInt(k[0]);
}
var v = $(v);
//v = v[0];
console.log("before_id");
console.log(before_id);
console.log("k");
console.log(k);
var id = before_id + k + "_";
v.attr("id", id);
console.log(v.html());
html_output += "<li>";
html_output += "<a href=\"#"+id+"\">";
html_output += v.html();
html_output += "</a>";
html_output += "<br/>";
process_siblings(v, level+1, id);
html_output += "</li>";
});
html_output +="</ul>";
}
@Velrok
Copy link
Author

Velrok commented May 4, 2012

Its buggy. If you have a structure like this:

h1 a
h2 b
h3 c
h2 bb
h3 cc

The script will mess up by uniting all h3 and list this unified set under each h2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment