Reputation: 139
I want to detect the first letter of the src in an img tag with JavaScript and display an alert if the first letter does not match 'l' :
HTML :
<!DOCTYPE html>
<html>
<body>
<script src="imgDetect.js"></script>
<img src="l.jpg" />
<img src="a.jpg" />
</body>
</html>
Javascript :
x = document.getElementsByTagName('img').getAttribute('src');
if (x.charAt(0)!=='l'){
window.alert("message")
}
The problem is that the getAttribute
does not work with thegetElementsByTagName
.
The alert will show if getElementsByTagName
is replaced by getElementById
, (for only detecting single elements),
I would like it work across all tags in getElementsByTagName
Upvotes: 0
Views: 1496
Reputation: 388316
It is because getElementsByTagName returns a NodeList object, which is an array like object with reference to multiple elements.
So document.getElementsByTagName('img')
does not have a method called getAttribute
, calling that will result in error. Instead you need to iterate through the list and test each element
x = document.getElementsByTagName('img');
for (var i = 0; i < x.length; i++) {
if (x[i].getAttribute('src').charAt(0) !== 'l') {
window.alert("message")
}
}
Demo: Fiddle
Also in your script, you have included the script in the page header, which when is executed the body of the pages is not yet loaded so, document.getElementsByTagName('img')
won't return any elements.
You can use the window's load method to execute your script or move the script to bottom of the page
Using onload
window.onload = function () {
//this part of the script will be executed after the document is loaded completely
var x = document.getElementsByTagName('img');
for (var i = 0; i < x.length; i++) {
if (x[i].getAttribute('src').charAt(0) !== 'l') {
window.alert("message")
}
}
}
Script at the bottom
<img src="l.jpg" />
<img src="a.jpg" />
<script src="imgDetect.js"></script>
Upvotes: 3
Reputation: 1037
getElementsByTagName
returns an array. You need to grab the element from the list before further accessing its attributes. Below is the updated code:
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++) {
if(images[i].getAttribute('src') !== 'l') window.alert("message");
}
Upvotes: 0