I've created an array of elements called $images (all the elements in the hidden class.) Then when I try to apply any method to just one element in the array, I get a $images[1].attr is not a function error. However, when I try $images.attr('id') for example without specifying the index of the array, it works but gives me the result for the first element in the array only.
$images = $(".hidden");
alert($images[1].attr('id'));
What's going here and how can I apply methods to single elements in an array? By the way, I'm certain there are at least two elements in the array as I tested it for this.
If you want still to have a jQuery object, rather than retrieving a native DOM element object, you need to use the eq function. This gets an element at a position in the array and returns it wrapped in the jQuery object, so you can do jQuery operations on it.
So:
$images.eq(1).attr('id');
If you only want the DOM element, you can use the square bracket notation or the get method. You can then look up a DOM property directly:
$images[1].id; // is the same as
$images.get(1).id;
Use .eq, like so:
$images = $(".hidden");
alert($images.eq(1).attr('id'));
Hope this helps!
$images[1] does not return a jQuery object, it is returning a dom element.
you want $($images[1]).attr('id')
The extra methods jQuery decorates the result array with are not present in the elements themselves. To get a specific element, you can use the eq selector or method:
$images = $(".hidden");
alert($images.eq(1).attr('id'));
or
$image = $(".hidden:eq(1)");
alert($image.attr('id'));
Related
When accessing an array, when is it appropriate to use the .eq() function?
For example, I have...
slides.eq(slidesLength-1).css("z-index", (slidesLength-1));
and later I have...
for(i=0; i<slidesLength-1; i++) {
$(slides[i]).css("left", "-100%");
}
In the first piece of code, the slideshow stops functioning if I don's use the .eq() function. However, the second piece seems to function whether I use the .eq() function or not. Why is this?
slides is not an array. It's a jQuery object. The .eq() method returns you the element at the specified index as a jQuery object.
While jQuery objects may not be arrays, they can pretend to be by having a length property as well as properties corresponding to the indexes. (Since they are not arrays, you can't call methods like .pop(), .forEach(), etc. on them.)
When you do slides[i], you are actually getting the DOM element, not a jQuery object. The $() function turns the DOM element into a jQuery object.
So, when you do slides.eq(1), internally jQuery is doing $(slides[i]).
P.S. Objects, like jQuery objects, that pretend to be arrays are called "array-like objects". If you console.log(slides), it may look like an array. This is just your console trying to make things convenient for you. (See this question for more info: Creating array-like objects in JavaScript)
.eq() is a jQuery method which returns a jQuery object, while accessing by index returns plain DOM element. You should use eq() when you want to use jQuery methods (css() in this case) on the returned selection.
The reason $(slides[i]) works is because you're constructing a jQuery object by passing the plain element to $() constructor.
Your slides variable is not an Array, but a jQuery object.
.eq() returns a jQuery object, eventually empty if index is out of bounds, and a negative index is counted from the end.
.get() returns a DOM Element, or undefined if index is out of bounds, and a negative index is counted from the end.
[] returns a DOM Element, or throw an Error if index is out of bounds.
...
Additionally, jQuery methods let you interact with a set of elements as it was alone. So you if you do:
slides.css("left", "-100%");
It is applied on every matched elements contained in the jQuery object. It is unnecessary to loop over them.
...
Also the preferred way to loop over matched elements is using the each() method:
slides.each(function (i, el) {
var $el = $(el);
});
...
Also it is an established convention to prefix jQuery variables with a $ sign; it let you to easily differentiate DOM elements from jQuery objects. But that's only a matter of taste.
I have a jQuery array of <span>s and I'd like to get just one of them as a jQuery object so that I can string additional methods on it. Something like $mySpans[2] (which returns a string), or $mySpans.get(2), (which returns the DOM element directly).
I know that this will work:
$($mySpans[2]).someJQueryMethod( ... );
...but it seems a little redundant. What is the right way to do this?
Like this:
$myspans.eq(2).method();
jsFiddle Demo
You are going to want to use eq. Note that it will return the jQuery object wrapped element at that index, so if you only have one match you should use 0 (which follows that 2 will return the third of the set).
var $thirdMatch = $mySpans.eq(2);//== jQuery object with third match
var htmlElement = $thirdMatch[0];//== actual dom element
var matchedHtml = $thirdMatch.html();// call some jQuery API method
It is common practice when storing jQuery objects to use a $variableName for readability purposes.
Could someone tell me what the jQuery equivalent of this would be?
var shapes=document.getElementsByTagName("shapes")[0];
thisCircle=shapes.getElementsByTagName("circle")[index];
There are a few ways to do it. Here's how I'd write it:
$('shapes').first().find('circle').eq(index)
You can just use the tags directly in the CSS selector and use modifiers like :first to let the CSS selector engine do most of the work for you and to create the fewest intermediate jQuery objects.
.eq(index) selects the index item from all the items found and returns a jQuery object. Directly indexing it with array syntax like [index] will return a DOM object (not a jQuery object):
$("shapes:first circle").eq(index)
The step by step description of what is going on here is this:
Find the first shapes object.
Find all circle objects that are descendants of that first shape object and construct a jQuery object that contains all those circle objects.
Call the eq() method on the jQuery object to make a new jQuery object that contains only the index circle object (e.g. only the 3rd one).
$("shapes:eq(0) circle").eq(index);
$('shapes').eq(0).find('circle').eq(index)
I think this should work:
$('[name="shapes"]').first().find('circle').eq(index);
In my javascript, I have a function which will return an element present in the HTML page .i have this stored in a variable and now want to do some kind of traversal in that using jquery methods like parent/fadeIn/fadeOut etc.
How can i do that.? My current code which returns the object is
var currentObject= GetThatObject();
Now i really want to play with this object like what we do with a typical jQuery object which we get like
var curObj=$("#tatElement")
You just do this:
var curObj = $(currentObject);
jQuery can take not only selector strings but HTML elements as arguments as well. It will just take that element, wrap it in its jQuery object and you can then use it the same way as if you had used a selector string. (It is actually a little more efficient because jQuery doesn't have to parse the selector and find the element).
I just started using jQuery, and various sources suggest that the following should be used to reference an element by ID:
$("#imgThumbnail")
theoretically making something like this possible:
$("#imgThumbnail").src;
But my testing indicates that something like $("#imgThumbnail") returns an array, making the following necessary:
$("#imgThumbnail")[0].src;
Do I really need to reference by the index of the array every time I am trying to reference something by ID (i.e., var oObj = $("#someobjectid")[0]; )?
You should get the src attribute to get the value
$("#imgThumbnail").attr('src');
This post explains what the $ function returns and various ways to use it.
$(selector)
Returns a jQuery object, which could contain a number of DOM elements.
$(selector)[0] or $(selector).get(0)
Returns the first result as an actual DOM element.
$(selector).eq(0) or $($(selector).get(0))
Returns the DOM element wrapped in a jQuery object so that we can do stuff like:
$(selector).eq(0).addClass("deleted").fadeOut();
$(specifier) will return a collection, so yes if you want to call something on an individual member you need to pick which one. In most cases though there is a collection operator you can use to achieve the same result. For instance, you could call $('#imgThumbnail').attr('src', 'value')
You should bear in mind that it's not really an array, it's a jQuery object which, among other things, allows array-style access
$(whatever)
returns the jQuery object. On the jQuery object you can do jQuery and jQuery plugin things, eg. .text() to return the text inside the element or .css("background", "pink") to make the element(s) pink.
Since src isn't a jQuery thing you cannot access it. src is however both a HTML attribute, and you can access those with the attr method:
.attr("src")` and `.attr("src", "http://www.example.com/myimage.png")
src is also a DOM-property and you can access DOM-properties using [index] or by iterating through the jQuery object with each:
.each(function(){
this.src = "http://www.example.com/myimage.png";
})
I don't think you should be using .src with jQuery.
Try $("#imgThumbnail").attr('src');
(this will read the src attribute, you set it with a second arg if you like)
See here:
http://docs.jquery.com/Attributes/attr
to set the src attribute use
$("#imgThumbnail").attr("src", value)
if you use something like a class selector or tag like so
$("img").attr("src", value)
It will modify all the image src attributes on the page. Hence the $ function returns an array.
And you do not need to reference it specifically.