I would like to know if it was possible using Javascript to find an image tag by its alt text. For instance I have this tag: <img src="Myimage.jpg" alt="Myimage">
would there be a way to obtain the tag by looking for the "Myimage" alt attribute?
views:
64answers:
3
+5
A:
There will undoubtedly be a jQuery solution posted soon enough. To do it without, the following will work:
function getImagesByAlt(alt) {
var allImages = document.getElementsByTagName("img");
var images = [];
for (var i = 0, len = allImages.length; i < len; ++i) {
if (allImages[i].alt == alt) {
images.push(allImages[i]);
}
}
return images;
}
var myImage = getImagesByAlt("Myimage")[0];
Tim Down
2010-05-26 15:40:10
A:
This wouldn't be so hard if NodeList implemented Iterable. This implementation puts filter into the prototype of NodeList, which may not match everyones taste but I prefer concise access to my data structures.
<html>
<head>
<script type="text/javascript">
// unfortunately NodeLists do not have many of the nice Iterate functions
// on them, here is an incomplete filter implementation
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 ;
}
// loops through the img tags and finds returns true for elements that
// match the alt text
function findByAlt(altText) {
var imgs = document.getElementsByTagName('img').filter(function(x) {
return x.alt === altText ;
}) ;
return imgs ;
}
// start the whole thing
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
2010-05-26 15:52:10
Note you'll get an array back since there is nothing in the DOM spec about having unique alt tags.
Mike
2010-05-26 15:52:56
Unfortunately the extension of `NodeList` rules out IE (at least up to and including version 7, I don't have 8 to hand to test).
Tim Down
2010-05-26 16:01:33
Ah, luckily/unfortunately I operate in a world without IE. What does IE present as the return of getElementsByTagName?
Mike
2010-05-26 17:33:15
I believe that it is a `NodeList` of sorts, but there's no direct access to a `NodeList` constructor function.
Tim Down
2010-05-26 18:10:18
Ah right, well thanks for that :) /me goes to read the jquery source
Mike
2010-05-26 18:47:11