How do I receive a title from an image for the value of a variable?

2

I was trying to do this:

var imagens = document.getElementsByTagName('img');

After I print this image, it does not work, it prints [object HTMLCollection] .

    
asked by anonymous 26.05.2015 / 22:41

2 answers

4

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

Fiddle

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.

    
26.05.2015 / 22:47
1

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;
    
29.05.2015 / 13:51