Jump to content

Get all heading tags on page and create anchor links to them?


Recommended Posts

I've got some long HTML files that are basically a software manual. Each section is started with a <h3> tag. What I want to do is create a script that will find all the <h3> tags in the document and create a list of links to each section and use the <h3> tags as anchors. Has anyone done this sort of thing before or have any ideas?

Link to comment
Share on other sites

Well, to start, you can get all the h3s in a document by doing the following

var h3s = document.getElementsByTagName("h3");

Then, once you have all the h3s, you could loop through them and either use the pre-existing ID of each h3 to create the anchor or use a new id

// first, create an empty array of links.  we'll add links// as we find h3s.var links = new Array();for(var i = 0; i < h3s.length; i++){	var h3 = h3s[i];	if(h3.id == "")  // is there an id?	{		h3.id = "h3_" + i;  // we'll just create an id	}	// now we create the links.  we'll use the h3's id as the anchor	// and the h3's innerHTML as the text that people can click on.	var link = document.createElement("a");	link.href = "#" + h3.id;	link.appendChild(document.createTextNode(h3.innerHTML));	// now we'll add that link to our array of links.	links[links.length] = link;	// or, if you prefer:	// links.push(link);}

Now that you have the array of links, you can put them somewhere.

var container = document.getElementById("MyLinkContainer");for(var i = 0; i < links.length; i++){	container.appendChild(links[i]);}

I haven't really tested this, but it should point you in the right direction.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...