GET ELEMENT BY ATTRIBUTE VALUE (PLAIN JAVASCRIPT)
function getElementByAttributeValue(attribute, value) {
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].getAttribute(attribute) == value) {
return allElements[i];
}
}
}
In case of multiple elements with the same attributes this will only return the first one.
EXAMPLE
Sometimes I use elements like <header role="masthead"> in my site to be able to style the site's header (masthead) differently than other header elements, for example post headers. To select this element in JavaScript I'd now use:var headerElement = getElementByAttributeValue('role', 'masthead');
In case of multiple elements with the same attributes this will only return the first one.
EXAMPLE
Sometimes I use elements like <header role="masthead"> in my site to be able to style the site's header (masthead) differently than other header elements, for example post headers. To select this element in JavaScript I'd now use:var headerElement = getElementByAttributeValue('role', 'masthead');
