value in .each() loop - javascript

when i use jQuery .each() function, it is give me index and value of current element.
I have a this code
$('.scrollbar').each(function (index, value) {
//some code
});
the value is an DOM or jQuery object

It's the underlying DOM object. It's easy to be proven:
$('.scrollbar').each(function(index, value) {
alert(value.jquery);
});
shows undefined.
Whereas:
$('.scrollbar').each(function(index, value) {
alert($(value).jquery);
});
shows the version of jQuery which is attached to all jQuery objects.

You can also use this:
$('.scrollbar').each(function (index, value) {
var DOM = this,
jq = $(this);
});
The value refers to the same object as the this object, so it will be the DOM object.

It is a DOM object. To get the jQuery object you can use $(value).

It refers to the current DOM element that your Jquery function is reffering to...
In this case your DOM element which has a class of .scrollbar is currently referred to...
As niels says, use "this" pointer to access the current DOM element.
Hope this helps :)

Related

What does $('<div>').parent() return?

I'm working on a jQuery widget that attaches events to the widget's parent, but I'm unable to tell if it has a parent.
For example;
var x = $('<div>');
x.mywidget();
........... in mywidget
_create : function () {
var y = this.element.parent() === undefined ? this.element : this.element.parent();
y.bind(....);
}
I need to check if the widget has been added to the DOM before I do the bind statement. If it has not been added to the DOM, then I'll just bind this.element.bind(....) instead.
The problem is that $('<div>').parent() returns a jQuery object! I was expecting that it would return undefined.
So I'm wondering what parent could it be returning when it shouldn't have a parent?
You may use myDiv.parent().length to know if the jQuery set is empty or not.
But this will yield false positives if the object wasn't removed from the DOM directly but it parent was.
If you want a reliable detection, then, you should use jQuery.contains(document.documentElement, myDiv).
It will always return an object. If you want to see whether anythings in the object, you can check for .length == 0, so $("<div>").parent().length == 0 would be your check.
Check the length of the jQuery object returned. If your div has no parent, the jQuery object returned by .parent will wrap zero elements.
All jQuery DOM searching and manipulation methods return a jQuery collection with 0 or more elements. $("<div>").parent() returns a collection with no elements (an empty collection). You can still call any jQuery method on it, but without being tied to a DOM element what you can do is very limited. It will have .length of zero, and the callback will not be reached when iterating over with .each.
I would check the length of the jQuery object since jQuery will always return an object.
it will be always a parent, can be the body for example
use jquery data for example to set your init marker
var wasInit = ( $(this).data("mypluginwasinit") !== undefined );
if(wasInit) return;
$(this).data("mypluginwasinit","yes");

why is jQuery selector property undefined within each()?

Given the following code, why does the selector property work in the first instance but not the second? Aren't they both jQuery objects?
<span class='tst'>span</span>​
var tst = $('.tst');
console.log(tst.selector);
// prints '.tst'
$('.tst').each(function() { console.log(this.selector);});
// prints undefined​​​​​​​
this, in the context of the .each() loop, is not a jQuery object, so the selector property is undefined.
You need to make it a jQuery object first: $(this).selector
However, it should be noted that the selector property will return an empty string while inside the .each() loop.
Edit
If you absolutely need the selector property within the .each(), one option would be to cache your selector:
var cached = $('.tst');
cached.each(function() {
console.log(cached.selector); // Will display ".tst"
});
​
this != $(this)
In your first case tst is a reference to the jQuery object, but in the second this is simply the corresponding DOM element.
Within an .each() loop the .selector property is not available, however. To access '.tst' you can do $(this).attr("class") (when you use a class selector) -- though if you already use it in the each you can just cache it in a variable before hand.
Note that this will return all of the classes for that elements, so you can parse it later if it has more than one.
The best workaround based on your exact description is this:
var $tst = $(".tst");
$tst.each(function() {
console.log($tst.selector); //prints .tst
});
However I can't see any reason why you really need to do this.
Working Demo http://jsfiddle.net/wA6Yv/ or http://jsfiddle.net/a3CYR/2/
this != $(this)
If you keen: jQuery: What's the difference between '$(this)' and 'this'?
code
var tst = $('.tst');
console.log(tst.selector);
// prints '.tst'
$('.tst').each(function() {
alert($(this).text());
});
// prints undefined

How to iterate through jQuery elements

I want to be able to see what's inside the tags that jQuery finds. How come the following doesn't work?
$("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
alert(($this).html);
});
What's the right way to do this?
$this => $(this)
.html => .html()
So this should do it:
$("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
alert($(this).html());
});
Note that html() function just uses the innerHTML property, so it can be a lot simpler:
$("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
alert(this.innerHTML);
});
The current element within a jQuery each iteration can be accessed via this (not $this).
There's a small caveat, however: the this in a jQuery iteration refers to each element's underlying DOM object, not the jQuery object. You can use this code, then:
$("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
alert(this.innerHTML);
});
You don't need to build a jQuery object from the raw DOM object on each iteration — an element's inner HTML is already present in the DOM object, and there's no need for extra work.

Can't call $.data on object inside function

I'm playing around with the jQuery $.data function, and I'm running in to some trouble. If I do like this:
(function($){
$.fn.testData = function() {
var obj = $(this);
obj.text($.data(obj,'test'));
}
})(jQuery);
var element = $("#test");
$.data(element,'test','hej');
element.testData();
this comes out as undefined. Why?
EDIT:
It works just fine if I use the elem.data(key) function, like this:
(function($){
$.fn.testData = function() {
var obj = $(this);
obj.text(obj.data('test'));
}
})(jQuery);
var element = $("#test");
element.data('test','hej');
element.testData();
but I just saw an slideshow by Paul Irish, which claims that elem.data is 10x slower than $.data(elem):
http://paulirish.com/2009/perf/
(function($){
$.fn.testData = function() {
var obj = $(this);
obj.text($.data(obj[0],'test'));
}
var element = $("#test");
$.data(element[0],'test','hej');
element.testData();
})(jQuery);
Here is the jsFiddle: http://jsfiddle.net/TdJHq/
jQuery.data (doc jQuery.data) works on DOM elements, not on jQuery elements. So you must extract the real element under your jQuery selector.
obj.text($.data(obj[0],'test'));
This is what #alexl explained.
But there is also a .data() method, that works on a jQuery selector, so you could use:
// getter
obj.text($obj.data('test'));
// setter
obj.text($obj.data('test','toto'));
And you may have mixed both.
The problem is that you are creating different objects for attaching and retrieving the data. Whenever you call $(selector), you are creating a new jQuery object and this it will be different than the one you attached the data to.
Here is a simple example:
$.data($('#test'),'test','hej');
alert($.data($('#test'),'test'));
It will give you undefined.
That is why $.data expects a DOM element and not a jQuery object. No matter how you retrieve a certain DOM element, the reference is always the same.
So either pass the DOM element ($('#test')[0]) or better, use $('#test').data().

jQuery: .each how to reference matched object

how do i get a reference to the element that matched? 'this' is not correct.
For example here I am trying to alert with the elements value.
//how do i get this to reference the object it matches.
$("#txtFirstName,#txtLastName,#txtDOB").each(
function() { alert(this.val()); }
);
Try:
$("#txtFirstName,#txtLastName,#txtDOB").each(
function() { alert( $(this).val() ); }
);
It is this, but to use val() you need a jQuery object.
$(this).val();
In that context this is a reference to the actual DOM element. You will need to wrap that into a jQuery object in order to use the val() function.
$(this).val()

Categories