How to receive a title(title) from an image to the value of a variable?

Asked

Viewed 245 times

2

I was trying to do it that way:

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

After I print this image, it doesn’t work, it prints [object HTMLCollection].

2 answers

4


This happens because the method getElementsByTagName() returns a collection of DOM elements. You have to access, in this collection, the desired element and then its attribute title:

// Por ex, pegando o título da primeira imagem
imagens[0].title

Fiddle

This way, unlike the accepted answer, you can iterate on the collection:

for (var i = 0; i < imagens.length; i++) {
}

But to access only one image, the accepted answer is the most correct.

1

You can get the title (title) so much for the id (ID), as by name (NAME) image, thus avoiding error if there are multiple images in the script, or inclusion of images above it. What would change if used imagens[0].title; For the [0] indicates that it is the first.

define an id in the image. Ex.: <img src="imagem.jpg" id="imagem1" title="Meu titulo"/>

Script

var ConteudoTitulo = document.getElementById('imagem1').getAttribute("title");

This way, even if you add new images and/or change the positions, you don’t need to change the script.

Following is a code template to see how it works: https://jsfiddle.net/cp1dchds/

To use in older browsers, the recommended would be to use the native method:

var ConteudoTitulo = document.getElementById('imagem1').title;
  • Important! When declaring Document.getelementsbytagname('img'), without a method in front, it returns the object, for this reason it displays [Object Htmlcollection], as it has more than one IMG. Even if there is only one image, it always needs to define the method. Each object has compatible method types. I only recommend using by name (getElementsByName) or tag name (getelementsbytagname) if it is sequential, because changing the order of an element can modify the result in some cases.

Browser other questions tagged

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