[英]How do i access 'src' attribute of <img> tag in javascript?
<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 ? 我如何访问img标签的'src'属性? im above code it gives null value so whats wrong ?
我上面的代码它给出了空值,所以什么是错的?
You can use src
on your image directly. 您可以直接在图像上使用
src
。 Also, you don't need .innerHTML
. 此外,您不需要
.innerHTML
。
Demo: http://jsfiddle.net/ThinkingStiff/aU2H2/ 演示: http : //jsfiddle.net/ThinkingStiff/aU2H2/
document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg' ).src;
HTML: 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>
alert(document.getElementById('your_image_id').getAttribute('src'));
First off, you shouldn't use .innerHTML at the end as attributes don't have innerHTML data. 首先,你不应该在最后使用.innerHTML,因为属性没有innerHTML数据。 Secondly, JS is very fragile with how it handles children when it comes to whitespace.
其次,JS在涉及空白时如何处理儿童是非常脆弱的。 I would recommend targeting the image by ID as others have pointed out.
我会建议像其他人指出的那样通过ID定位图像。 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. 引用ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase节点,然后找到它下面的图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.