0

I have a problem where i am getting the window size in jquery then looping througbh three img elements to apply the width to the inline style on the fly.

The issue is that when the foreach loop is run i get this error in the console Uncaught TypeError: Object [object Object] has no method 'setAttribute'

I have put a breakpoint in the loop and applied setAttribute to this and it appears to work fine. I dont understand why when it loops through the array it is not treating each array item as an object but seems to be trying to access the array as an object.

var windowsize = $(window).width();

$(window).resize(function() {

    windowsize = $(window).width();

    $( "#imgs img" ).each(function (){
        $( this ).setAttribute("style","width:"+windowsize+"px");

    });                                                                 
});

sorry if this isn't clear

any help will greatly be appreciated

2 Answers 2

2

The setAttribute is a js method and not a jquery method.

You either need to use the raw js method on the DOM element directly or use the jQuery version .attr() of the method.

Both the below ways are the same, but personally using the native js feels better.

$( this ).attr("style","width:"+windowsize+"px");
this.setAttribute("style","width:"+windowsize+"px");
Sign up to request clarification or add additional context in comments.

2 Comments

But if you do use the jQuery version, you could do away with the loop to make it shorter: $("#imgs img").width(windowsize);
Thanks very much, I actually didnt know I couldnt use raw js methods on jquery objects. that helped alot!
1

.setAttribute() is a native Javascript method. As you're using jQuery, use .attr() instead:

$(this).attr("style", "width:" + windowsize + "px");

or:

$(this).css("width", windowsize + "px");

or even better:

$(this).width(windowsize);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.