I was trying to do this:
var imagens = document.getElementsByTagName('img');
After I print this image, it does not work, it prints [object HTMLCollection]
.
I was trying to do this:
var imagens = document.getElementsByTagName('img');
After I print this image, it does not work, it prints [object HTMLCollection]
.
This happens because the getElementsByTagName()
method returns a DOM element collection . You have to access, in this collection, the desired element and then its title
attribute:
// Por ex, pegando o título da primeira imagem
imagens[0].title
In this way, unlike the accepted answer, you can iterate over the collection:
for (var i = 0; i < imagens.length; i++) {
}
However, to access only one image, the accepted answer is the most correct.
You can get the title ( title
) by both the id ( ID
), such as by name ( NAME
) of the image, thus avoiding error if there are multiple images in the script, or adding images above of this. What would change if you use imagens[0].title;
Because [0]
indicates that it is the first .
Set an id in the image.
Ex: <img src="imagem.jpg" id="imagem1" title="Meu titulo"/>
Script
var ConteudoTitulo = document.getElementById('imagem1').getAttribute("title");
Here's a sample code to see how it works: link
To use in older browsers, the recommended method would be to use the native method:
var ConteudoTitulo = document.getElementById('imagem1').title;