Using jQuery to get descdent nodes in DOM - javascript

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

Related

How to get the k-th element in a jQuery set ... AS A JQUERY ELEMENT

So I encounter this situation often and I want to figure out a better way of going about it. I using the naming convention prefixing my jQuery elements with $ so that I can distinguish them from DOM elements. For example, the following:
$pointers = $('#pointer-box div.pointer');
The problem with that is, if I want to get the 3rd in the result as a jQuery, I have to do
$($pointers[2])
which looks awkward. Unless there's a better way of doing this?
You can use .eq() jQuery method
$pointers = $('#pointer-box div.pointer');
var element=$pointers.eq(2);
Given a jQuery object that represents a set of DOM elements, the .eq()
method constructs a new jQuery object from one element within that
set. The supplied index identifies the position of this element in the
set.

array.eq() vs. array[] in Javascript and Jquery

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.

Make get() returning a jQuery object

Is there a way to have get() returning a jQuery object instead of "just" the DOM element?
Example:
$("div").get(0) returns [<div></div>] instad of <div></div>.
I'd like to prevent overwrapping like $($("div).get(0)) because the query will get a little bit longer than the example and I fear the readability gets lost. I'd rather not use variables to save unnecessary DOM elements in the RAM, either.
Use eq() to return the jquery object instead of get()
$("div").eq(0)
Given a jQuery object that represents a set of DOM elements, the .eq()
method constructs a new jQuery object from one element within that
set. The supplied index identifies the position of this element in the
set, jQuery doc
You would use eq:
$("div").eq(0)
Use eq() instead , which will return jQuery object
$("div").eq(0)
Also try this also:
$('div:first')

applying methods to single elements in an array - jquery/javascript

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

Jquery - Reference by ID - Supposed to return an array?

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.

Categories