Add anchor links to the headers in my posts

This articles describes some JS that will automatically append a link SVG icon for headers in post content that have an id attribute.

SVG Elements and namespacing

The SVG namespace is not naturally entwined with HTML, so if you've ever tried to create an SVG element, you might have noticed it doesn't work using the standard document.createElement DOM API method.

SVG elements are namespaced under, so creating them needs to be done with the document.createElementNS DOM API.
document.createElementNS('', 'svg')
Similarly, the use elements for re-using an SVG definition defined using the xlink namespace.
var use = document.createElementNS('', 'use');
use.setAttribute('xmlns:xlink', '');

This example creates the Get link icon using the use element and xlink namespace.

The JS

The custom HTML gadget executes the following javascript to create the elements.
document.querySelectorAll('.Blog h2, .Blog h3, .Blog h4').forEach(
  h => {
    if (! || h.querySelector('.anchor')) return;
    h.innerText = h.innerText + ' '; // Add some whitespace.
    var a = document.createElement('a');
    a.href = '#' +;
    a.setAttribute('class', 'anchor');
    var svg = document.createElementNS('', 'svg');
    svg.setAttribute('class', 'svg-icon-24');
    var use = document.createElementNS('', 'use');
    use.setAttribute('xmlns:xlink', '');


Popular posts from this blog

Add syntax highlighting to my Blog

Change my post timestamps to a custom format

Add snippets to the Emporio theme