Skip to content

Instantly share code, notes, and snippets.

@amit08255
Created October 2, 2022 12:30
Show Gist options
  • Save amit08255/257f332c806359bf736d5025d73eab7f to your computer and use it in GitHub Desktop.
Save amit08255/257f332c806359bf736d5025d73eab7f to your computer and use it in GitHub Desktop.
HTML hierarchy based on heading
function nest_headings(headings) {
	/*
		Return an array of nested heading objects of the form:
		{
			heading: html element
			level: integer 1-6
			children: child headings
		}
	*/
	var heading_levels = {
		'H1': 1,
		'H2': 2,
		'H3': 3,
		'H4': 4,
		'H5': 5,
		'H6': 6,
	}
	function get_level(heading) {
		return heading_levels[heading.tagName];
	}
	var parents = [{heading: null, level: 0, children: []}];
	headings.forEach(function(h) {
		var level = get_level(h);
		while (level <= parents[parents.length-1].level) {
			parents.pop();
		}
		var h_obj = {heading: h, level: level, children: []};
		parents[parents.length-1].children.push(h_obj);
		parents.push(h_obj);
	});
	return parents[0].children;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment