JSFiddle - React, Tailwind, and code Playground
by silkster
HTML
<p title="me">1</p>
<p title="you">2</p>
<p title="me">3</p>
<p title="me">4</p>
<p title="you">5</p>
<p title="you">6</p>
<p title="you">7</p>
<p title="me">8</p>
CSS
.blue { color: blue; font-weight: bold; font-size: 14pt; }
JavaScript
//Filters the given array to those which when passed into matcher return true
Array.prototype.where = function(matcher) {
var result = [];
for (var i = 0; i < this.length; i++) {
if (matcher(this[i])) {
result.push(this[i]);
}
}
return result;
};
function GetElementsByAttribute(tag, attr, attrValue) {
//Get elements and convert to array
var elems = Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
//Matches an element by its attribute and attribute value
var matcher = function(el) {
return el.getAttribute(attr) == attrValue;
};
return elems.where(matcher);
}
// demo using jQuery for DOM ready:
$(function() {
var elems = GetElementsByAttribute('p', 'title', 'me');
for(var x = 0; x < elems.length; x++) {
elems[x].setAttribute('class', 'blue');
}
});