Search code examples
javascripthtmlforeachonclickinnerhtml

Pass text inside a tag to another tag using forEach


EDIT: I don't understand why this was marked as duplicated since the previously question didn't reply my issue. Yes, it is about passing using querySelector but how do I do this using forEach? Please revise this.

I'm trying to make a figcaption to be displayed according to its associated image. It's a photo gallery I took the code from this video.

This piece of code works as fine as is showed in the video:

document.querySelectorAll('.image-container img').forEach(image =>{
    image.onclick = () =>{
        document.querySelector('.popup-image').style.display = 'block';
        document.querySelector('.popup-image img').src = image.getAttribute('src');
    }
});

But when I try to use the code I created to pass the figcaption's text to the desired tag (see .finalCaption below), I got [HTML ObjectCollection] as string. This is the code that I tried and didn't work:

document.querySelector('.finalCaption').innerHTML = image.getElementsByClassName('caption');

This is the HTML code from where the tag text should've come from (it's several .images because it is a photo gallery):

<div class="image-container">
    <div class="image">
        <figure>
            <img src="image.jpg" alt="">
            <figcaption class="caption">Some figcaption text</figcaption>
        </figure>
    </div>
</div>

And this is where it should go when clicked (it should have been displayed as a popup image like in lightbox):

<div class="popup-image">
    <span>&times;</span>
    <figure>
        <img src="image.jpg" alt="">
        <figcaption class="finalCaption">Figcaption text go here</figcaption>
    </figure>
</div>

What am I missing? How can I use each image's figcaption to be displayed everytime it is clicked?

Thank you very much.


Solution

  • innerHTML takes a string, but getElementsByClassName returns an HTMLCollection. The engine attempts to turn this into a string and you get "[HTML ObjectCollection]".

    What you want is the text value, not the element. Edit:

    You don't need to use getElementsByClassname because you are passing in the element here .forEach(image =>{ You can get the element's text with .textContent

    document.querySelector('.finalCaption').innerHTML = image.nextSibling.textContent