html5 - Javascript - getAttribute not working with getElementsByTagName -


i want detect first letter of src in img tag javascript , display alert if first letter 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 getattribute not work thegetelementsbytagname.

the alert show if getelementsbytagname replaced getelementbyid, (for detecting single elements), work across tags in getelementsbytagname

it because getelementsbytagname returns nodelist object, array object reference multiple elements.

so document.getelementsbytagname('img') not have method called getattribute, calling result in error. instead need iterate through list , test each element

x = document.getelementsbytagname('img'); (var = 0; < x.length; i++) {     if (x[i].getattribute('src').charat(0) !== 'l') {         window.alert("message")     } } 

demo: fiddle


also in script, have included script in page header, when executed body of pages not yet loaded so, document.getelementsbytagname('img') won't return elements.

you can use window's load method execute script or move script bottom of page

using onload

window.onload = function () {     //this part of script executed after document loaded     var x = document.getelementsbytagname('img');     (var = 0; < x.length; i++) {         if (x[i].getattribute('src').charat(0) !== 'l') {             window.alert("message")         }     } } 

script @ bottom

<img src="l.jpg" /> <img src="a.jpg" /> <script src="imgdetect.js"></script> 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -