How to add image text change in JS / HTML

Basically, what I'm trying to do, I'm trying to change the image 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 does not affect the text of the image. If someone can help, it will be great, thanks!

+4
source share
3 answers
  • A tag is imageused inside elements svg, a tag is used for HTML img, and they are closing tags <img src="" />.
  • It is not InnerHTML, it is InnerHTML, and you do not even need to use it in your case.
  • To set an attribute alt img, just 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!" />
Run codeHide result
+4

img tag . . getElementById ( "Elem ID Here" ). , innerHTML i. innerHTML InnerHTML.

+1

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

Install it like this:

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

Change it like this:

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

Snippet of working code:

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

image.alt = 'xyz';

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

For your code you need to follow these 3 steps:

  • <image>Use a tag instead of a tag <img>.
  • Wrap <img>in <figure>and add <figcaption>.
  • Instead of retrieving an image by ID, select <figcaption>and modify it innerHTML.

Here it is!

Snippet of working code:

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>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1569013/


All Articles