iProgramApps
iProgramApps

Reputation: 53

How to add change an image's text in JS / HTML

Basically, what I'm trying to do is I am trying to change an images alt "text".

In other words: I'm trying to do something like this:

<!DOCTYPE html>
 <html>
  <head>
   <script type="text/javascript">
    var num = 0;
    setInterval(function(){asdfjkl.InnerHTML="Number: " + num}, 500);
    setInterval(function(){num+=1;}, 100);
   </script>
  </head>
  <body>
   <image id="asdfjkl" src="asdf.png">Hello!</image>
  </body>
 </html>

But the script has no effect at all on the image's text. If someone could help that would be awesome, thanks!

Upvotes: 4

Views: 955

Answers (3)

Rahul Desai
Rahul Desai

Reputation: 15501

To change the alt text, you need to set it first! :)

Set it like this:

<image id="asdfjkl" src="asdf.png" alt="abc">Hello!</image>

Change it like this:

document.getElementById('asdfjkl').alt = 'xyz';

Working Code Snippet:

var image = document.getElementById('asdfjkl');

image.alt = 'xyz';

console.log(image);
<image id="asdfjkl" src="asdf.png" alt="abc">Hello!</image>

For your code, you need to do following 3 things:

  1. Instead of <image> tag use <img> tag.
  2. Wrap your <img> in <figure> and add a <figcaption>.
  3. Instead of fetching the image by ID, fetch the <figcaption> and change its innerHTML.

Thats it!

Working Code Snippet:

var num = 0;
setInterval(function(){document.getElementsByTagName('figcaption')[0].innerHTML="Number: " + num}, 500);
setInterval(function(){num+=1;}, 100);
<figure>
  <img id="asdfjkl" src="asdf.png" />
  <figcaption>Hello!</figcaption>
</figure>

Upvotes: 0

Weafs.py
Weafs.py

Reputation: 22992

  1. The image tag is used inside svg elements, for HTML use img tag and they are self closing tags <img src="" />.
  2. It's not InnerHTML, it is innerHTML and you don't even need to use it in your case.
  3. To set the alt attribute of the img, simply use asdfjkl.alt.

var asdfjkl = document.getElementById('asdfjkl');
var num = 0;
setInterval(function() {
  asdfjkl.alt = "Number: " + num
}, 500);
setInterval(function() {
  num += 1;
}, 100);
<img id="asdfjkl" src="" alt="Hello!" />

Upvotes: 4

dr_dev
dr_dev

Reputation: 522

You need to use img tag, instead of image. You cannot use the element id directly like this. Use getElementById("Elem ID Here"). Also innerHTML in your case is with a capitalised i. Use innerHTML not InnerHTML.

Upvotes: 1

Related Questions