Skip to content

Instantly share code, notes, and snippets.

@wpgaurav
Created January 19, 2024 08:57
Show Gist options
  • Save wpgaurav/64442edf2e18b21b3e253cfc4b589191 to your computer and use it in GitHub Desktop.
Save wpgaurav/64442edf2e18b21b3e253cfc4b589191 to your computer and use it in GitHub Desktop.
Add aria-labels to important HTML tags (works with any theme).
document.addEventListener('DOMContentLoaded', function() {
// Select specific tags.
var tags = document.querySelectorAll('header, main, footer, article, nav');
// Function to convert ID to a readable format.
function formatIdToReadableText(id) {
// Replace non-alphanumeric characters with spaces and trim any extra spaces.
var formatted = id.replace(/[^a-zA-Z0-9]/g, ' ').trim();
// Capitalize the first letter of each word.
return formatted.replace(/\b\w/g, function(char) {
return char.toUpperCase();
});
}
// Iterate through each tag.
tags.forEach(function(tag) {
// Check if the ID attribute exists.
if (tag.id) {
// Format the ID and set it as the aria-label.
tag.setAttribute('aria-label', formatIdToReadableText(tag.id));
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment