2 * AnchorJS - v0.1.0 - 2014-08-17
3 * https://github.com/bryanbraun/anchorjs
4 * Copyright (c) 2014 Bryan Braun; Licensed MIT
7 function addAnchors(selector) {
10 // Sensible default selector, if none is provided.
12 selector = 'h1, h2, h3, h4, h5, h6';
13 } else if (typeof selector !== 'string') {
14 throw new Error('AnchorJS accepts only strings; you used a ' + typeof selector);
17 // Select any elements that match the provided selector.
18 var elements = document.querySelectorAll(selector);
20 // Loop through the selected elements.
21 for (var i = 0; i < elements.length; i++) {
24 if (elements[i].hasAttribute('id')) {
25 elementID = elements[i].getAttribute('id');
27 // We need to create an ID on our element. First, we find which text selection method is available to the browser.
28 var textMethod = document.body.textContent ? 'textContent' : 'innerText';
30 // Get the text inside our element
31 var roughText = elements[i][textMethod];
33 // Refine it so it makes a good ID. Makes all lowercase and hyphen separated.
34 // Ex. Hello World > hello-world
35 var tidyText = roughText.replace(/\s+/g, '-').toLowerCase();
37 // Assign it to our element.
38 // Currently the setAttribute element is only supported in IE9 and above.
39 elements[i].setAttribute('id', tidyText);
41 // Grab it for use in our anchor.
44 var anchor = '<a class="anchorjs-link" href="#' + elementID + '"><span class="anchorjs-icon"></span></a>';
46 elements[i].innerHTML += anchor;