8

I have several headers on a page, and I need to populate a navigation box on each page that links to the appropriate anchor."

However none of my headers are anchored. I have too many pages to do this manually. can anyone come up with a clean jquery solution?

2 Answers 2

13
function addAnchors(){
    //loop through all your headers
    $.each($('h1'),function(index,value){
        //append the text of your header to a list item in a div, linking to an anchor we will create on the next line
        $('#box-anchors').append('<li><a href="#anchor-'+index+'">'+$(this).html()+'</a></li>');
        //add an a tag to the header with a sequential name
        $(this).html('<a name="anchor-'+index+'">'+$(this).html()+'</a>');
    });
}
4
  • Sweet! I will definitely try this.. Thanks for sharing! Commented Feb 28, 2011 at 23:50
  • No problem, has helped me out more than once. Commented Mar 1, 2011 at 0:01
  • 1
    Instead of the last line in your code, you could have used .wrapInner() (api.jquery.com/wrapInner), so you end up with $(this).wrapInner('<a name="anchor' + index + '" />');
    – Mottie
    Commented Mar 1, 2011 at 0:07
  • If you want to do this for a jekyll page, they've already added id to headers for you. All you need is this script.
    – SimplGy
    Commented May 14, 2015 at 13:49
1

Actually, you can link to every tag with an id. So reading out the id's of the h1 and or setting them would do it, and would result in cleaner html (no sudden css-suprises in the future when styling your a-tag).

1
  • 1
    Well, if not, you can add one. Seems like less of a hack than putting an anchor element around it. So I'd suggest: check if id present, if so, append this id to the #box-anchors, if not, create own id, append this to #box-anchors, and add this id to the h1. That way you won't disturb the structure of the html and are more certain all other js and css will keep working. (for instance: what if the h1 is the first child of the div, and some script uses that property? or what if a css rule or js selector uses the next-sibling of the h1?)
    – markijbema
    Commented Mar 1, 2011 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.