Skip to content

Instantly share code, notes, and snippets.

@Ugotsta Ugotsta/code-to-kbd.js
Last active Mar 13, 2019

Embed
What would you like to do?
JavaScript to automatically convert keypress shortcuts in isolated code elements like <code>Enter</code> to kbd elements like <kbd>Enter</kbd>.
let code = document.querySelectorAll("code");
code.forEach( el => el.classList.add("prettyprint") );
code.forEach( i => {
let found = false;
let h = i.innerHTML.toLowerCase();
let c = ['tab', 'esc', 'return', 'enter'];
if ( c.includes(h) ) found = true;
if ( h.length === 1 ) found = true;
c = ['ctrl', 'alt', 'cmd', 'shift', 'win', 'super', 'kbd'];
let s = c.some( e => {
if ( h.startsWith(e + "-") ) return found = true;
});
let u = h.charCodeAt(0);
if (u === 55356 ) {
i.innerHTML = i.innerHTML.substring(2);
found = true;
}
if (!found) return;
let kbd = document.createElement('kbd');
kbd.innerHTML = i.innerHTML;
i.parentNode.replaceChild(kbd, i);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.