5
<html>
<head></head>
<body>
<div id="ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase">
<div style="width:100%;text-align:center;"><img src="http://www.xyz.com/aaa.gif" id="ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg" alt="Loading" /></div>        </div>
<script>
q= document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase').childNodes[1].getAttribute('src').innerHTML;

alert(q);

</script>
</body>
</html>

how do i access 'src' attribute of img tag ? im above code it gives null value so whats wrong ?

4 Answers 4

21

You can use src on your image directly. Also, you don't need .innerHTML.

Demo: http://jsfiddle.net/ThinkingStiff/aU2H2/

document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg' ).src;

HTML:

<html>
<head></head>
<body>
<div id="ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase">
    <div style="width:100%;text-align:center;"><img src="http://placekitten.com/100/100" id="ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg" alt="Loading" /></div>        
</div>
<script>
    q = document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg' ).src;
    alert(q);
</script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

9
alert(document.getElementById('your_image_id').getAttribute('src'));

Comments

0

With jQuery:

var imgsrc = $("#ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg").attr("src");

jQuery is the most robust way IMO.

6 Comments

The user not tagged the question in jquery
I'd suggest using jQuery for this kind of thing - it handles it very well
Yeah we all know the best way is jquery..i too agree..but the asker wants in javascript
jQuery is Javascript... I don't see reason for that or @Matt Wolfe's answer to get downvoted.
jQuery may be JavaScript, but not all JavaScript is jQuery. User asked for JS, not jQuery. It is clear the user is using vanilla JS to achieve this.
|
0

First off, you shouldn't use .innerHTML at the end as attributes don't have innerHTML data. Secondly, JS is very fragile with how it handles children when it comes to whitespace. I would recommend targeting the image by ID as others have pointed out. Alternatively you could use something like this:

q= document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase').getElementsByTagName("img")[0].getAttribute("src");

to reference the ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase node and then find the image underneath it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.