serps
serps

Reputation: 221

Foreach loop in jquery

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

Upvotes: 0

Views: 148

Answers (2)

Matt R. Wilson
Matt R. Wilson

Reputation: 7575

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

Upvotes: 2

emerson.marini
emerson.marini

Reputation: 9348

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

Upvotes: 1

Related Questions