Home > Software design >  Regex - How to get src and alt from Image
Regex - How to get src and alt from Image

Time:10-22

I need to get from all the images the src and alt of the html code. I managed to get it but I have the following problem:

  • If the image has no alt, it does not detect me the image. In these cases I need to get only the src.

The following code works with problem: enter image description here

enter image description here

CodePudding user response:

If you have a set of img elements in your HTML. You can also get the src and alt value by looping a HTMLCollection.

Demo :

const imgCollection = document.getElementsByTagName('img');

for (let item of imgCollection) {
  console.log('src :', item.src)
  console.log('alt :', item.alt)
}
<img src="https://example.com/image" alt="example1">
<img src="https://example.com/image">

  • Related