Search code examples
javascriptindexofsrc

Changing image src depending on which word is in the element


I want to change the image displayed depending on which word is in the element, which will change frequently. I have tried using the indexOf method, to try and seach for the keyword which will decide whether to show a specific image in element 1 or element 2, but without luck.

<div class="main>
    <h1 id="nextGame" onLoad="nextGames()">Aug 25, 2019: Home against Genoa</h1>
    <p id="homeTeam"><img src="" id="teamHome"> vs <img src="" id="teamAway"></p>
</div>


<script>
var nextGame1 = document.getElementById("nextGame").indexOf("Home");
 if (nextGame1 !== -1); {
    document.getElementById("homeTeam").src = "asroma2.png";
 } else { 
    document.getElementById("teamAway").src = "asroma2.png";
 }
</script>

I expected my code to be able to see if the element "nextGame" had the string "Home" in it. If so, the image source of "homeTeam" would be changed to my specified src, and if not "teamAway" would be assigned the src.

This was clearly not the case. Does anyone know what I did wrong?


Solution

  • Using document.getElementById("nextGame") will result in complete HTML Tag instead of the text present in the tag. You can use document.getElementById("nextGame").innerText to get the text inside the tags and then you can use the indexOf operator to identify if "Home" is present in it or not. The complete code will be written as follows:

    <div class="main>
      <h1 id="nextGame" onLoad="nextGames()">Aug 25, 2019: Home against Genoa</h1>
      <p id="homeTeam"><img src="" id="teamHome"> vs <img src="" id="teamAway"></p>
    </div>
    
    
    <script>
     var nextGame1 = document.getElementById("nextGame").innerText.indexOf("Home");
     if (nextGame1 !== -1) {
         document.getElementById("homeTeam").src = "asroma2.png";
     } else { 
         document.getElementById("teamAway").src = "asroma2.png";
     }
    </script>
    

    You have also closed the if statement with a semicolon and also used an additional closing bracket at the end, both of which will throw a syntax error.