jquery get one object in an array as an array - javascript

With jQuery I can do
$('#some_id').find('div').first()
or
$('#some_id').find('div').last()
and get an answer like
[<div>​something</div>​]
If I do
$('#some_id').find('div')[3]
I get answer like
<div>​something</div>
How do I specify an index in array and get an array just with that object?
I would love to do something like
$('#some_id').find('div').somefunc(3)
and get
[<div>​something</div>]
I know there is slice(), but I feel like there is some simpler function that I have over looked in my hours of searching.
I know there is :nth-child() but again, it feels like there is some other function that I can call the way I call first() or last().
I am trying to chain some functions together to have one line that does what I need.
If there is not other ways, then I guess that is fine. I just wanted to make sure.
Thanks!

You can use .eq():
$('#some_id').find('div').eq(3) // This will return the fourth div inside #some_id
Since .eq() is 0-based index, if you want to get the third div you need to use:
$('#some_id').find('div').eq(2)

You can also use .get(index)
$($('#some_id').find('div').get(3)); // jQuery obj
or
[$('#some_id').find('div').get(3)]; // Array
The .get() method grants access to the DOM nodes underlying each
jQuery object. If the value of index is out of bounds — less than the
negative number of elements or equal to or greater than the number of
elements — it returns undefined.

Related

How to treat the return value of jQuery functions that return a bunch of elements

How to can I treat the return value of jQuery functions that would return a bunch of DOM elements. E.g. I'm using the .nextAll() function, that returns a bunch of elements, does it? Can I store the return value in a JS array? Sooner or later I want to iterate through those elements. I know there's the jQuery .each() function that would help me out here. Nevertheless, for training and understanding issues I first want to do it step by step.
I'm pretty sure, this basic question is answered somewhere, but I searched for an answer and did not find anything useful for me. Maybe I didn't find the right words. So please be kind.
jQuery functions typically returns a bunch of DOM elements, it masquerades as an array.
If you run something like:
$('p').css('background-color', 'red');
jQuery will build an array of all p elements, and then applies the css() function to each of them.
If you want a single DOM item, use get with an index:
$( "li" ).get( 0 )
So, .nextAll() also typically returns a number of elements, so it is behaving just like jQuery typically does.
each() is a handy-dandy function that operates on arrays, so it will of course operate just fine on jQuery objects:
$('li + li').nextAll().each(function(i){
//glorious code
});
You could also do this:
var nexts = $('li + li').nextAll();
$.each(nexts, function(i){
//Glorious code!!
});
Hope that makes things clearer!
You can just assign it to a variable:
var $els = $(selector).nextAll();
This way, $els will be a jQuery wrapper (array-like object) of the elements.
If you want to have an array of the elements instead, you can use
var arr = [].slice.call($els);
As the documentation of .nextall() says, it returns jQuery
A jQuery object contains a collection of Document Object Model (DOM)
elements that have been created from an HTML string or selected from a
document. Since jQuery methods often use CSS selectors to match
elements from a document, the set of elements in a jQuery object is
often called a set of "matched elements" or "selected elements".
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().

jQuery - Get element from array as jQuery element?

If I call
$(".myClass")
I get an array of elements. If I now want to get the first element as jquery element I would do something like this:
$($(".myClass").get(0))
So I wrap the DOM-Element, which I get from the array again with the jQuery operator. Is there a more elegant way to do this? Some get method, which returns a jQuery element for example?
Use the eq() method:
$(".myClass").eq(0)
This returns a jQuery object, whereas .get() returns a DOM element.
.eq() lets you specify the index, but if you just want the first you can use .first(), or if you just want the last you can use (surprise!) .last().
"I get an array of elements."
No you don't, you get a jQuery object which is an array-like object, not an actual array.
If you plan to use jQuery much I suggest spending half an hour browsing through the list of all methods.
Or use the each method to traverse.
$(".myClass").each(function () {
console.log($(this).html())
})

Convert jquery selectors to array

I need to be able to store the current selectors in the current viewport and then 10 seconds check if they are still in the users current viewport.
My solution for this was to store the selectors in an array and then in 10 seconds compare the old selectors against the new and see if any match. If they do... do something.
So i believe using .each and build the array, unless somebody has a more elegant solution to this?
$('.gridContainers:in-viewport')
This will return a standard selectors.
Calling $(selector) returns an array-like jQuery object, not an actual JavaScript array, though for the purposes of what they're trying to do converting it to an actual array may be unnecessary.
This is how one would turn a selector into an native Javascript array.
$(selector).toArray()
Jquery.toArray()
With ES6 :
Array.from($(selector)); // return JS array
Try Out FIND method as Below:
$('element').find('selection');
This will give all selected elements to Array. Hope this helps

LINQ-For-Javascript Nested Arrays

The Linq-For-Javascript library contains functions that convert between "jQuery objects" and "Enumerable objects": toEnumerable() and TojQuery(). Consider the difference between these two lines:
$('tr'); // returns array of tr
$('tr').toEnumerable().TojQuery(); // returns array of tr[1]
Converting from jQuery to Enumerable and back to jQuery does not give you what you started with. The end result is an array of arrays of elements, with each sub-array having a length of 1. I do need to make use of Enumerable, so this is just a convenient example of my problem.
This means that to get the id of an element, you'd need to do the following:
$('tr')[0].id; // returns "myID"
$('tr').toEnumerable().TojQuery()[0][0].id; // returns "myID"
I'm surprised of this, because even though I've allegedly gone back TojQuery(), the object returned by TojQuery() does not work with typical jQuery calls:
$('tr').find('td').length; // returns 170 (in my case)
$('tr').toEnumerable().TojQuery().find('td').length; // returns 0 (BAD)
I would like it if both lines returned 170, but apparently Linq-For-Javascript doesn't work that way.
So, my questions:
Why is this?
Am I doing it wrong?
If not, any good workarounds? (convert array of 1-element arrays to array of elements?)
Thanks!
JQuery handles operations according to types. In the first line of the code, if finds all HTML TR objects and by the help of this information it can attach necessary functions to the found objects.
$('tr').find('td')
However, it could not understand after you change it to enumarable object since it is no longer seems to be a HTML Object instead it becomes any other type of object. Thus, jquery cannot attach a function to it.
$('tr').toEnumerable()

handling splice with associative arrays in javascript

I have an array called as wcs declared using var wcs= new Array();.
I do add items like this, wcs[indx] = value. where i will keep on changing the indx value, so at times, my array will be looking like this
wcs[2] ='a'; wcs[5]=')';
when i call the splice method on this array, all the created indices are re-indexed, meaning they become reset from 0...
how to avoid this in javascript & jQuery
Write your own splice method that works the way you want. If you specify the input, processing and expected output, you might get some help with that.
If you simply want a copy of the array, you may be after the concat method.

Categories

Resources