user3164891 user3164891 - 1 month ago 6
jQuery Question

jQuery Cannot read property 'setAttribute' of undefined

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?

Answer

To check if an element exists you should've used the code:

if($$('#' + id + 'popup-image').length > 0){
    console.log("found");
}else{
    console.log("fail");
}

To set the attribute you should

if (src) { $$('#' + id + ' a.product-image img').first().attr("src", src);
           $$('#' + id + ' a.popup-image img').first().attr("src", src); 
         }