It is not so difficult if NodeList has implemented Iterable. This implementation puts the filter in a NodeList prototype that may not suit every taste, but I prefer compressed access to my data structures.
<html>
<head>
<script type="text/javascript">
NodeList.prototype.filter = function(testFn) {
var array = [] ;
for (var cnt = 0 ; cnt < this.length ; cnt++) {
if (testFn(this[cnt])) array.push(this[cnt]) ;
}
return array ;
}
function findByAlt(altText) {
var imgs = document.getElementsByTagName('img').filter(function(x) {
return x.alt === altText ;
}) ;
return imgs ;
}
function load() {
var images = findByAlt('sometext') ;
images.forEach(function(x) {
alert(x.alt) ;
}) ;
}
</script>
</head>
<body onload="load()">
<img src="./img1.png" alt="sometext"/>
<img src="./img2.png" alt="sometext"/>
<img src="./img3.png" alt="someothertext"/>
</body>
</html>
Mike source
share