Convert jquery selectors to array - javascript

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

Related

jquery get one object in an array as an array

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.

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().

d3.select.reverse() has no effect

I'm confused why reverse() works for regular arrays but not d3.select objects, which are based on the array as well. I'm basically trying to traverse the elements I selected from the DOM in reverse order via each but the following seem to traverse them in the same order:
d3.selectAll('.someclass').each(function(){console.log(this);})
d3.selectAll('.someclass').reverse().each(function(){console.log(this);})
I figured it out. d3.select IS an array, it's in their documentation (https://github.com/mbostock/d3/wiki/Selections), but it's a container array of size 1, the actual array of DOM elements is contained within that first element. The following, while a bit uglier, works as expected:
selection = d3.selectAll('.someclass')
selection[0].reverse()
selection.each(function(){console.log(this);})
I'm not a big fan of using the sort solution (the elements are technically already sorted, and I'd also need to figure out the current order in the DOM tree to compare by).
There is no .reverse() method in D3. Note that selections are not arrays and come with their own implementation of methods to manipulate them. To sort the elements in a particular way, use .sort().

Remove all the DOM elements with a specific tag name in Javascript

How can I remove all the elements with a specific tag name using Javascript. For example, I did the following:
var els = document.getElementsByTagName("center");
and it returned an array of all the center elements. How may I remove all these elements?
Coming from Remove all child elements of a DOM node in JavaScript and JavaScript DOM remove element I know that I can loop through els, find the parent of each element and then remove that specific node. But is there anyother way provided by javascript. Like we can do $('center').remove() in jquery and it removes all the elements with center tag. Anything similar to that in Javascript?
With the mention that you still loop over the elements (there is no way to avoid that), you can do this:
Array.prototype.slice.call(document.getElementsByTagName('center')).forEach(
function(item) {
item.remove();
// or item.parentNode.removeChild(item); for older browsers (Edge-)
});
DEMO: http://jsbin.com/OtOyUVE/1/edit
Some notes on slice:
document.getElementsByTagName doesn't return an array, it returns a live list with a length
property. That is why it is needed to first convert it into an array (Array.prototype.slice does that for any object with the length property). By doing that you eliminate the problem of the list being live (gets updated when you change the DOM) and you also get the other array functions to work (like forEach) which have a more functional syntax for looping.
"it returned an array of all the center elements."
Well, it returned an array-like object (a live NodeList or an HTMLCollection depending on the browser).
"How may I remove all these elements?"
You have to loop through the list removing them one at a time as you mentioned later in your question. If you find yourself doing that a lot, encapsulate the looping inside a function so that you don't have to repeat it.
"we can do $('center').remove() in jquery and it removes all the elements with center tag. Anything similar to that in Javascript?"
jQuery is a collection of JavaScript functions, so it can't do anything JavaScript can't do. jQuery's .remove() method (like most other jQuery methods) will loop internally, it just saves you having to think about it. So that comes back to what I already mentioned above, encapsulate the loop/remove code in a function so that you can use it from any part of your code.

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

Categories

Resources