Skip to content
Advertisement

JS Change HTML img src based on specific text found in h1 tag

I’ve posted a similar question regarding switching HTML text snippets (see JS Switch HTML content based on specific text included in h1 tag), for which the replies were hugely helpful. From these replies, I used the following code to change the HTML text snippet:

<h1>This is about Red Apples</h1>
<span id="colour"></span>
window.addEventListener("load",function(){ 
  const h1 = document.querySelector("h1"),
      description = document.querySelector("#colour"),
      colours = [
        { colour: "red", description: "red description" },
        { colour: "blue", description: "blue description" }
      ]
  
description.innerText = colours.filter(f => h1.innerText.toLowerCase().includes(f.colour))[0]?.description
  },false);

I now wish to modify the code to change the img src depending on some text (a different string of text from that required in my previous post) included in the h1 tag.

After lots of trial and error I can’t figure out how to modify this code to change the image src on the same page. The closest I’ve got so far, but using the “if/else” method, is:

<h1>This is about Red Apples</h1>
<img id="fruitimage" src="default-image.jpg"/>
var map = {
    'red apples': 'redapples-image.jpg',
    'blue blueberries': 'blueberries-image.jpg',
    'yellow bananas': 'yellowbananas-image.jpg'
};

function influenceImage(source, map) {
    if (!source || !map) {
        return false;
    }
    else {
        var text = source.textContent || source.innerText;
        for (var word in map) {
            if (map.hasOwnProperty(word) && text.indexOf(word) !== -1) {
                return map[word];
            }
        }
    }
}

document.getElementById('fruitimage').imageNode.src = influenceImage(document.getElementsByTagName('h1')[0], map);

However, I still cannot get this to work. I’m really hoping someone can help! Many thanks in advance!

Advertisement

Answer

For what I see you have 2 errors in your code.

1 – remove .imageNode.

2 – you need to convert text to lower-case as the object key you are trying to get is in lower-case, use .toLowerCase()

var map = {
  "red apples": "redapples-image.jpg",
  "blue blueberries": "blueberries-image.jpg",
  "yellow bananas": "yellowbananas-image.jpg",
};

function influenceImage(source, map) {
  if (!source || !map) {
    return false;
  } else {
    let text = source.textContent.toLowerCase() || source.innerText.toLowerCase();3
    for (var word in map) {
      if (map.hasOwnProperty(word) && text.indexOf(word) !== -1) {
        return map[word];
      }
    }
  }
}

document.getElementById("fruitimage").src = influenceImage( document.getElementsByTagName("h1")[0], map);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement