How do I get the title of an image by JavaScript?

1

How do I get the title of an image and display it on a alert ?

    
asked by anonymous 16.02.2016 / 14:06

2 answers

9

You just need to select the image (either by ID or another selector), then access the property title .

var outraDiv = document.getElementById("outra-div");
var imagem = document.getElementById("imagem");
imagem.addEventListener("click", function (event) {
    outraDiv.textContent = imagem.title;
});
<div id="outra-div"></div>
<img id="imagem" src="http://image005.flaticon.com/1/svg/72/72716.svg"title="Award" />
    
16.02.2016 / 14:11
1

You can also do inline

<div id="div"></div>
<img src="" id="imagem" onclick="document.getElementById('div').innerHTML=this.title" title="título" />

And if you have many divs you can do by function

 <script> 
function titulo(div,titulo) {
 document.getElementById(div).innerHTML=titulo; } 
</script>

 <div id="div"></div> <img src="" id="imagem" onclick="titulo('div',
 this.title)" title="título" />
    
19.03.2016 / 20:58