Trying to add a text to all cards in a dynamic page with Global Javascript via Google Optimize, but it's looping

36 Views Asked by At

Trying to add a text before the image on all cards, in a dynamic page. there are 1700 images so ı thought it's only doable via javascript, since it's on Google Optimize, only vanilla is allowed.

I put this:

var images = document.querySelectorAll(".car-card .car-card__image");

images.forEach(function(image){ 
  image.before("Hello world");
});

It actually puts the text, but when I check it via debug mode, it's adding the text for forever, so I see,

Hello worldHello worldHello world....

How to fix this?

Cheers

1

There are 1 best solutions below

1
babak-maziar On

you need create a empty tag before any image and put the text in it.

in yuor Html:

<div></div>
<img src="..." class="car-card">

and in yout javascrtipt code

document.querySelectorAll(".car-card .car-card__image").forEach(img=>{
    img.previousSibling.innerHTML = 'HELLO WORD';
})

But if you can't add a tag before the photo, there is another way that is not interesting

document.querySelectorAll("img").forEach(img=>{
    var p = img.previousSibling;
    if( p && p.nodeName=='#text' )
        p.nodeValue = 'HELLO WORD';
    else
        img.before('HELLO WORD')

})