Home > Net >  Javascript IF statement with DOM
Javascript IF statement with DOM

Time:12-24

I'm having trouble with an IF statement that checks a DOM element and replaces the current src with a new src. In the code below, I know the source for sceneImageID is the image after the ==, yet the IF statement does not trigger.

var scene = document.getElementById('sceneImageID').src;
        console.log("scene before if: "   scene);
        if (scene.endsWith == "Media/Town/Town_bw.png") {
            scene = "Media/Town/Town_bw_noscrap.png";
            console.log("inside if statement: "   document.getElementById("sceneImageID").src);
        }

EDITS: added the .endsWith piece, but I'm having the same issue of it not entering the IF statement.

The first console returns: http://34.68.254.120:8080/Media/Town/Town_bw.png

Thanks in advance.

CodePudding user response:

Relative sources will get expanded to a full URL, so consider checking for ending with instead.

if (document.getElementById('sceneImageID').src.endsWith("Media/Town/Town_bw.png")) {

CodePudding user response:

Just to make sure that you are setting the image ID:

<img id="ImgTown" src="Media/Town/Town_bw.png">

<script>
var checkImage = document.getElementById("ImgTown");
if (checkImage.src == "Media/Town/Town_bw.png") 
{
    checkImage.setAttribute("src", "Media/Town/Town_bw_noscrap.png");
}
</script>

This script will just be triggered if you load the page with the Media/Town/Town_bw.png as the image source. Else, you must have an event like "onClick" calling this using a function.

  • Related