i am trying to make a script that changes the link of an image to a new image within a div if the h2 element contains any of the text within the array const targetTexts
. there is an issue with the if statement, if i remove the part && targetTexts.includes(h3Element.textContent.toLowerCase()
, which i need to check against the words in the array, and leave it as and leave it as if (h3Element)
, it works and replaces every single image with the new image. but, i need to check the contents of the h2 element against the array so i need that line.
the h3 element textContent outputs stuff like this : “Beauty in motion Attractive young mixed race woman in jeans shirt shaking her head and smiling while standing outdoors, Generative AI 29139243 Stock Photo at Vecteezy”
so i dont get why its not working if there is matches
setTimeout(() => {
console.log('SCRIPT BEGINS RUNNING');
// select all search results
const results = document.querySelectorAll('div[jsname="N9Xkfe"]');
const aiImg = 'https://www.shutterstock.com/image-vector/anti-ai-sign-no-aigenerated-600nw-2289609093.jpg';
console.log(results);
// array of targeted text
const targetTexts = [
'ai', 'ai generated', 'generate ai', 'ai art',
'stable diffusion', 'midjourney', 'generative ai',
'ai-generated'
];
// loop through each result element
results.forEach(result => {
// check if the element has an h2 child with targeted text
const h3Element = result.querySelector('h3');
console.log('H3 ELEMENT' + h3Element.textContent);
console.log('FOR EACH LOOP BEGINS');
if (h3Element && targetTexts.includes(h3Element.textContent.toLowerCase())) {
// get the img element and replace the link
console.log('THE H2 ELEMENT EXISTS!!!');
const imgSrc = result.querySelector('img');
console.log('IMAGE SRC: ' + imgSrc);
imgSrc.setAttribute('src', aiImg);
}
console.log('FOR EACH LOOP ENDS');
});
console.log('END OF SCRIPT');
}, 2000);
and here is an example of the console logs which i used to confirm i was selecting the correct elements: