[jQuery] Change image attribute based on variable

[jQuery] Change image attribute based on variable


Hi, pulling my hair out here.
When the page loads I'm collecting a variable from the url which
corresponds to the class of an image. I want to then change the image
source. I'm doing this because the page doesn't reload and the menu
needs to respond to the content if you get my meaning.
$url = location.href;
$hashtag = $url.search(/#/)
$url2 = $url.split("#", $hashtag);
$finalurl = $url2[1];
This is the code I use to get the class name. When I try to add
$finalurl to the attr (see below) it throws an error (undefined,
console.log shows it is defined within the if statement).
$($finalurl).attr("src", $($finalurl).attr("src").split(".").join
("_on."));
Full code:
$url = location.href;
$hashtag = $url.search(/#/)
$url2 = $url.split("#", $hashtag);
$finalurl = $url2[1];
counttemp = 0;
if (counttemp == 0) {
    console.log($finalurl);
    $($finalurl).attr("src", $($finalurl).attr("src").split(".").join
("_on."));
    counttemp = countemp + 1;
}
Any help would be greatly appreciated.