While clicking a button/trigger I need to change the folder path name from img/image.jpg to imgdark/image.jpg for all the instances of the specific class ".imageShift". What ever image name that is inserted in the image src should remain the same through out all the occurrences. Just the "img" folder path has to be replaced with "imgdark". I tried a code given below.
$('.themeColor').click(function () {
var getId = $(this).attr('id');
var imagePath = $('.imagePath');
if (getId === 'darkTheme') {
imagePath.attr('src', function (index, attr) {
return attr.replace('img', 'imgdark');
});
} else if (getId === 'lightTheme') {
imagePath.attr('src', function (index, attr) {
return attr.replace('imgdark', 'img');
});
}
});
The above code is working perfectly but on each click I am getting a console error as displayed below. I need to get rid of that console error and also make this work as it does already. Please help with this if anyone have done this already.
Uncaught TypeError: Cannot read property 'replace' of undefined
at HTMLLIElement.<anonymous> (homepage.js:1619)
at z (jquery-3.3.1.min.js:2)
at w.fn.init.attr (jquery-3.3.1.min.js:2)
at HTMLSpanElement.<anonymous> (homepage.js:1617)
at HTMLSpanElement.dispatch (jquery-3.3.1.min.js:2)
at HTMLSpanElement.y.handle (jquery-3.3.1.min.js:2)
if (getId === 'darkTheme')is there are multiple instances with same id(darkTheme or lightTheme )?attrexists before trying to replace it. There seems to be a case where either the attribute or theimagePathclass do not exists, so you cannot apply replace on it. I cannot really help you with a solution as i cant see the whole picture, but try using the debugger and step through your function and see why there are cases where the attribute doesn't exists.imgdarktoimgits actualy changing toimgdarkdark. Because replase changing not whole string but part of it imgdarkdark. You nedd to use regex in your replace