skip to Main Content

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:

enter image description here

2

Answers


  1. 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.

    if (!h3Element) return;
    
    const fullTextContent = h3Element.textContent?.toLowerCase() || "";
    
    /**
     * splitting just by a comma
     * feel free to tune this as you see fit
     */
    const textContents = fullTextContent.split(", ").map((t) => t.toLowerCase());
    
    /**
     * now we check if any of the `targetTexts` elements are 
     * included in any of those splitted text contents
     */
    if (targetTexts.some(target => textContents.includes(target)) {
      // do your stuff
    }
    
    Login or Signup to reply.
  2. The line targetTexts.includes(h3Element.textContent.toLowerCase()) is problematic.

    const targetTexts = [
        'ai', 'ai generated', 'generate ai', 'ai art',
        'stable diffusion', 'midjourney', 'generative ai',
        'ai-generated'
      ];
    
      const h3ElementTextContent = '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'; // copied from the question
      if (targetTexts.includes(h3ElementTextContent.toLowerCase())) {
          console.log('The string exists');
      } else {
          console.log('The string does not exist');
      }

    It will return the string does not exist, as Array.includes() does not work this way. If we change the h3ElementTextContent to "AI", the check will match, as the word "AI" lowercased is included in the targetTexts array.

    You should change the checking to (requires ES5+):

    const targetTexts = [
        'ai', 'ai generated', 'generate ai', 'ai art',
        'stable diffusion', 'midjourney', 'generative ai',
        'ai-generated'
    ];
    
    str = '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';
      
    if (targetTexts.some(function(v) { return str.toLowerCase().indexOf(v) >= 0; })) {
        console.log('The string exists');
    } else {
        console.log('The string does not exist');
    }

    This will return The string exists.

    Alternatively, you can use RegEx. See this answer for more details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search