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:
2
Answers
What you implemented is checking if any
targetText
elements contains the full H3 element text content. You need to separate the text content into smaller pieces to check if those smaller pieces match and not the whole thing.I see that the H3 element content text has segments separated by a comma (
,
) or a pipe (|
) but very sporadically, so you could split the content and check individually for each segment.The line
targetTexts.includes(h3Element.textContent.toLowerCase())
is problematic.It will return
the string does not exist
, asArray.includes()
does not work this way. If we change theh3ElementTextContent
to "AI", the check will match, as the word "AI" lowercased is included in thetargetTexts
array.You should change the checking to (requires ES5+):
This will return
The string exists
.Alternatively, you can use RegEx. See this answer for more details.