Grab HTML element via Javascript using getElementsByClassName

Asked

Viewed 1,660 times

2

What’s the problem with this javascript code? The function always returns error.

<!-- IMAGEM -->
<img class="coverPhotoImg photo img" src="ABC.JPG" alt="Foto 1">
<!-- IDENTIFICAÇÃO --->
<span class="hidden_elem enableFriendListFlyout outgoingButton" data-profileid="2015">Protocolo enviado.</span>
<script type="text/javascript">
//PELA LOGICA DEVERIA RETORNAR ABC.JPG
window.alert(document.getElementsByClassName('coverPhotoImg photo img').getAttribute('src'));
//PELA LOGICA DEVERIA RETORNAR 2015
window.alert(document.getElementsByClassName('hidden_elem enableFriendListFlyout outgoingButton').getAttribute('data-profileid'));
</script>

1 answer

4


The getElementsByClassName always returns you a list of the elements you found, even if it is only one, the correct code is:

document.getElementsByClassName("coverPhotoImg photo img")[0].getAttribute("src")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.