Q:

How can I get the src attribute of a child img element while looping through an array of divs?

I want to loop through some <div> tags and get the src attribute of the child <img> element but I am not sure how to do it. This is what I have so far.

const imgs = document.querySelectorAll(".imgs .imagecont");

imgClick = (event) => {
  console.log(event.target.src);
};

imgs.forEach(img => img.addEventListener("click", imgClick));
<div class="imgs">
  <div class="imagecont">
    <img src="assets/img1.jpeg">
  </div>
  <div class="imagecont">
    <img src="assets/img2.jpeg">
  </div>
</div>

Also, I have to use vanilla javascript.

A:

Try with Element.getAttribute()

The getAttribute() method of the Element interface returns the value of a specified attribute on the element.

const imgs = document.querySelectorAll(".imgs .imagecont");

imgClick = (event) => {
    console.log(event.target.getAttribute('src'));
};

imgs.forEach(img => img.addEventListener("click", imgClick));
<div class="imgs">
    <div class="imagecont">
        <img src="assets/img1.jpeg">
    </div>
    <div class="imagecont">
        <img src="assets/img2.jpeg">
    </div>
</div>

