I've implemented an image switch in my website. It worked fine but I broke it by altering to my wishes. The code was as following:
if (src) { $$('#' + id + ' a.product-image img').first().setAttribute("src", src);}
And i've changed it to:
if (src) { $$('#' + id + ' a.product-image img').first().setAttribute("src", src);
$$('#' + id + ' a.popup-image img').first().setAttribute("src", src);
}
I simply added a image source that need to be changed. But when I run it on my site I get the following error:
Uncaught TypeError: Cannot read property 'setAttribute' of undefined
I've checked if the element exists and if it could by found by adding the following code to my script:
if('#' + id + 'popup-image' == 0){
console.log("fail");
}else{
console.log("found");
}
And it returns found everytime. I've changed my code to this:
$$('#' + id + ' a.popup-image img').first().setAttribute("src", src);
But then I get the following error:
Uncaught TypeError: Cannot read property 'first' of null
How do I fix this?
setAttributeis a DOM node method. You are trying to use it on jQuery obj$$function? Note thatif('#' + id + 'popup-image' == 0){does not check if the element exists, it compares a string to the number 0, which won't ever be equal so will always log "found".'popup-image'part of thatifto'blah'- it'll still log "found". You have to pass that string to a function that looks for the DOM element (e.g., to the$$()function, whatever it is).