Created
January 19, 2024 08:57
-
-
Save wpgaurav/64442edf2e18b21b3e253cfc4b589191 to your computer and use it in GitHub Desktop.
Add aria-labels to important HTML tags (works with any theme).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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