Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each css is not a function

I have an jQuery object with 3 members:

var elements = $("#" + this.wrapperName + ">ul>li>a>img");
Object { 0: <img>, 1: <img>, 2: <img>, length: 3, prevObject: Object, context: HTMLDocument → JSUmstellung, selector: "#newsdesk>ul>li>a>img" }

I want to change eachs CSS-Property, so I made this:

elements.each(function(index, element) {
    element.css({
        "width": elemWidth,
        "height": elemHeight,
        "top": elemTop,
        "left": elemLeft
    });
}

When I run this code, I just get the following error:

TypeError: element.css is not a function

What am I doing wrong? Do I have to access my element in another way?

Thanks in advance!

like image 964
ovmcit5eoivc4 Avatar asked Aug 05 '14 14:08

ovmcit5eoivc4


People also ask

What is the use of the CSS() method in jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.

How to use not function in jQuery?

The not() is an inbuilt function in jQuery which is just opposite to the filter() method. This function will return all the element which is not matched with the selected element with the particular “id” or “class”. The selector is the selected element which is not to be selected.

How to loop jQuery function?

version added: 1.0.each( function ) The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.


1 Answers

The problem is that element is a DOM node, without access to jQuery methods, what you need to use is $(this) or $(element):

elements.each(function(index, element) {
    $(this).css({
        "width": elemWidth,
        "height": elemHeight,
        "top": elemTop,
        "left": elemLeft
    });
}

Or:

elements.each(function(index, element) {
    $(element).css({
        "width": elemWidth,
        "height": elemHeight,
        "top": elemTop,
        "left": elemLeft
    });
}

Or you could, instead, use cssText (if you really want to work with DOM nodes):

elements.each(function(index, element) {
    element.style.cssText = 'width: ' + elemWidth + '; height: ' + elemHeight + ' top: ' + elemTop + '; left: ' + elemLeft;
}

Bear in mind that, within each(function (index, element){ ... }); element is exactly the same as this (and, as a corollary, $(this) is the same as $(element)). I'm not sure quite what the benefit is, of using the element at all.

like image 97
David Thomas Avatar answered Sep 28 '22 10:09

David Thomas