|
-
Why doesn't my getAttribute work ?
<html>
<head>
<script type="text/javascript>
var a = document.getElementsByTagName("img").getAttribute("src");
alert(a);
</script>
<body>
<img src="www.google.com" alt="picture"/>
</body>
</html>
I want the browser to alert the src of the picture (www.google.com) but it never works !
Help much appreciated
Thanks in advance,
B.W
-
getElementsByTagName returns a collection (even if that collection is only one item, and the contents should be accessed by array notation.
getAttribute is only really necessary for non-standard attributes. The standard ones (like src) can be accessed directly:
Code:
var a = document.getElementsByTagName("img")[0].src;
-
Hi there brucewayne,
and a warm welcome to these forums. 
Further to what xelawho has said, there are some other reasons for your script failure.
You are missing a closing double quote here...
<script type="text/javascript> ...which means that the script will never run. 
Although you can set this...
var a=document.getElementsByTagName('img'); ...before the page loads, you cannot access the actual elements until after. 
This following will resolve these issues...
Code:
<script type="text/javascript">
var a=document.getElementsByTagName('img');
function init(){
for(c=0;c<a.length;c++) {
alert(a[c].getAttribute('src'));
}
}
window.addEventListener?
window.addEventListener('load',init,false):
window.attachEvent('onload',init);
</script>
coothead
-
woops. never even looked that far. nice one, coothead
-
Hi there xelawho,
thanks for the thumbs-up. 
coothead
-
Now what if..
Now, I don't understand all that window.onload code. So, to make it simpler for me, I'd like to use butttons.
HTML:
<img src="www.google.com" alt="picture"/>
<input type="button" onclick="alertit()"/>
Javascript:
<script type="text/javascript">
function alertit() {
var a = document.getElementsByTagName("img")[0].getAttribute("src");
alert(a);
}
Why doesn't this work either ?
-
 Originally Posted by brucewayne
Why doesn't this work either ?
Your code does not have a closing script tag. 
coothead
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|
Bookmarks