英文:
Retrieve the src from a image
问题
I'm trying to get the src in a specific image on my webpage. When I entered my code the output is an undefined error.
Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute')
This is the HTML code
<div class="team-member-image border-radius-5px overflow-hidden">
<img class="abc" alt="" src="images/team01.jpg">
</div>
This is the js
<script>
var pic = document.getElementsByClassName("abc")[0].getElementsByTagName("img")[0];
var src = pic.getAttribute('src');
console.log(src);
</script>
What can be the issue in this and how can I solve this.
英文:
I'm trying to get the src in a specific image on my webpage. When I entered my code the output is an undefined error.
Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute')
This is the HTML code
<div class="team-member-image border-radius-5px overflow-hidden">
<img class="abc" alt="" src="images/team01.jpg">
</div>
This is the js
`<script>
var pic = document.getElementsByClassName("abc")[0].getElementsByTagName("img")[0];
var src = pic.getAttribute('src');
console.log(src);
</script>`
What can be the issue in this and how can I solve this.
答案1
得分: 0
只需调用一次获取元素:
var pic = document.getElementsByClassName("abc")[0];
英文:
Just call once get element:
var pic = document.getElementsByClassName("abc")[0];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论