user3164891
user3164891

Reputation: 298

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?

Upvotes: 1

Views: 12870

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

If you want to use the JavaScript setAttribute() function, you have to access the HTMLElement within your jQuery object by referencing the first item of its array, [0], like so:

 $('#' + id + ' a.product-image img')[0].setAttribute("src", src);

Calling first() will return a jQuery object; with this approach you have to use attr() , as there is no setAttribute() method in jQuery.

Try:

 $('#' + id + ' a.product-image img').eq(0).attr("src", src);

or:

$('#' + id + ' a.product-image img:first').attr("src", src);

or you can use get() which takes an index argument, and passing 0 will return first element:

$('#' + id + ' a.product-image img').get(0).attr("src", src);

Upvotes: 3

Artur Adams
Artur Adams

Reputation: 68

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); 
         }

Upvotes: 1

Related Questions