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!
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!
Share Improve this question edited Jun 26, 2015 at 6:46 captainsac 2,4903 gold badges28 silver badges51 bronze badges asked Aug 5, 2014 at 14:18 ovmcit5eoivc4ovmcit5eoivc4 1634 silver badges13 bronze badges 1 |3 Answers
Reset to default 19The 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.
You have to wrap it in the jquery format. Like so:
elements.each(function(index, element) {
$(element).css({
"width": elemWidth,
"height": elemHeight,
"top": elemTop,
"left": elemLeft
});
}
notice the:
$(element)
You have to use $(this) selector inside the each loop
elements.each(function(index, element) {
$(this).css({
"width": elemWidth,
"height": elemHeight,
"top": elemTop,
"left": elemLeft
});
}
index
orelement
, you don't have to include them:elements.each(function() {
. Then use$(this)
in the function. – jwatts1980 Commented Aug 5, 2014 at 14:23