Store Jquery object and access later? - javascript

I'm trying to store Jquery object into an array and access later to apply Jquery methods.
Something like:
var myArr = [];
myArr.push($('div#id1'));
myArr.push($('div#id2'));
$(myArr).show();
This is not working

You're trying to execute the show method on the array passed to jQuery, not on each object, try something like this:
$.each(myArr, function(k, elem) {
$(elem).show();
})

If you insist on storing your jQuery objects in an array, you will need to map that array to a new jQuery object before being able to call jQuery methods on it to affect your stored objects.
You can use jQuery's .map() for that:
var myArr = [];
myArr.push($('div#id1'));
myArr.push($('div#id2'));
$(myArr).map(function(){ return this.toArray(); }).show();
JSFiddle

Why are you storing the items in an array to begin with? If you only need to perform operations over multiple items you can simply do either of the following:
$('selector1, selector2').operation();
$('selector1').add('selector2').operation();

Another way, all JQueried ^^ :
var myElements = $('div#id1');
myElements = myElements.add('div#id2');
myElements.show();
To reverse the .add() you can use .not :
myElements = myElements.not('.clazz');
myElements.hide();

Related

Retrieving single parts of a javasript/jquery object

Hi suppose I have a jQuery selector such as this:
var a = $(this);
var b = a.nextUntil("button").text();
This will retrieve all the DOM elements till the next button. I want to access all these DOM elements individually as separate objects. Is there way to do that?
If you want to execute a function for each of the elements, you can use .each
If you want all the objects to be in an array, you can do something like this:
var arr = a.nextUntil("button")
and then index it as an array.
console.log($(a[0]).text())

angularjs : iterate array with key value pairs

I am creating an array like the following:
var arr =[];
arr['key1'] = 'value1';
arr['key2'] = 'value2';
If is use this array in ng-repeat tag, it is not displaying anything. Is there any way to make it work?
<div data-ng-repeat='(key,value) in arr'>{{key}} - {{value}}</div>
Is there any way to make it work?
The way to go, is to creat plain object (instead of array)
// instead of creatin of an Array
// $scope.myArr = [];
// we just create plain object
$scope.myArr = {};
...
// here we just add properties (key/value)
$scope.myArr['attempt1'] = {};
...
// which is in this case same as this syntax
$scope.myArr.attempt1 = {};
Thee is updated plunker
Check more details what is behind for example here:
Javascript: Understanding Objects vs Arrays and When to Use Them. [Part 1]
Your associative array is nothing but an object, as far as JavaScript is concerned. IMO Associative arrays and Objects are almost same.
Ex: Your arr['key1'] = 'value1'; can be called as console.log(arr.key1);
To make your code work, you need to change the array declaration by removing [] and replacing with {} (Curly braces)
Like this var arr = {};

Converting data-* attributes to an object

I'm playing around with the attr-data-* attributes of HTML5 and the corresponding javascript dataset
I'm doing alot of dynamic form processing, so I end up getting stuff like this:
<input data-feaux="bar" data-fizz="buzz"/>
Since HTMLElement.dataset returns a DOM string map, the only way I can figure out how to convert it into an native object is:
var obj = JSON.parse(JSON.stringify(input_el.dataset))
Is there a better way to do this?
Edit:
Why would I want to do this? Let's say I have many, many of these elements. I want to loop through them all and push them into an array for processing later, i.e.
elements = document.querySelectorAll("input")
my_data_array = []
for(var i = 0; i < elements.length; i++) {
my_data_array.push(elements[i].dataset)
}
Now I have an array of objects, i.e. [{feaux: "bar", fizz:"buzz"}....] that I can work with.
However, when I don't convert the DOM string map into an object, the array doesn't get populated (i.e. the code above doesn't work)
Edit 2
Looking closer, it is actually a DOM string map, not an object. Correcting typos in the original question to reflect this.
You can use Object.assign
Object.assign({}, element.dataset)
For browsers that doesn't support Object.assign you can use polyfill
in es6 you can use the object spread.
{ ...element.dataset }
Don't forget about JSON.stringify and JSON.parse.
var data = document.getElementById('someElement').dataset;
data = JSON.parse(JSON.stringify(data));
According to Mozilla this should work all the way back to IE 8 without a polyfill.
Here's a little function to retrieve the element dataset as a normal object:
function datasetToObject(elem){
var data = {};
[].forEach.call(elem.attributes, function(attr) {
if (/^data-/.test(attr.name)) {
var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
return $1.toUpperCase();
});
data[camelCaseName] = attr.value;
}
});
return data;
}
Scooped up from:
Get list of data-* attributes using javascript / jQuery

Getting the default(?) element of a jQuery() selection

I am sure there is a simple solution.
The starting scenario was the following.
I create a <select> element and populate it dynamycally:
function CreateDropDown(name, id, optionList)
{
var combo = $("<select></select>").attr("id", id).attr("name", name);
$.each(optionList, function (i, item) {
combo.append("<option value='"+item.val+"'>" + item.el + "</option>");
});
return combo;
}
The aim was to extract the outerHTML. The following works right:
combo[0].outerHTML();
But I feel that indexing the array is very rough. At least in all that cases where the jQuery() function return a single element array.
Question
Whenever the jQuery() function return a single element array, is it possible to get the unique element without array indexing?
Demo
jQuery objects are inherently collections of DOM objects, and there is no syntactic way to treat a jQuery object as wrapper around a single item.
jQuery documentation suggests using get method to access individual DOM elements. It does not comment on performance difference between indexing operator and .get(), but it does say that "each jQuery object also masquerades as an array", so it would be ok to assume that indexing operator just adds another method call.
If you "feel that indexing the array is very rough", you could write your own nice helper method. Something like a:
window.$$ = function(){
return jQuery.apply(jQuery,arguments)[0];
}
Usage:
var combo = $$("<select></select>");
console.log( combo.outerHTML );
Use .get() to get the html elements.
http://api.jquery.com/get/

How do I store multiple jQuery selectors in a javascript variable?

Obviously it's a good idea to store jQuery selectors in variables if they are used more than once (not a good idea if used only once).
My question is, how do you store multiple selectors, that are used interchangeably, in a variable.
For instance, let's say I select $('#object1, #object2), then later on I select `$('#object1'). How would I create a variable that can be combined with other variables to create multiple selectors.
If I were to write it like this:
var object1 = "#object1";
var object2 = "#object2";
$(object1 + "," + object2);
I would only be referencing the string #object1, and not the actual selector.
So how do I store multiple selectors in variables, so they can be used interchangeably?
The problem is not the selector string, the problem is the query of the DOM element. "Problem" means, it's expensive. That is why you should only query an element once and store a reference to it.
var object1 = $('#object1'),
object2 = $('#object2');
object1.some_method();
update
In reference to your comment:
jQuery offers the .add()help method which allows to concat jQuery objects:
object1.add(object2).method();
Not completely sure I understand what you mean. You want to store the jQuery objects so you don't have to continually search for them like some sort of cache?
var cache = new Object();
cache['#object1'] = $('#object1');
cache['#object2'] = $('#object2');
To retrieve the jQuery values, you'd merely have to call cache['#object1'].
You can use .add():
var object1 = $('#object1'), object2 = $('#object2');
object1.add(object2).addClass('couple');
Or,
var multiple = [object1[0], object2[0], ...];
$(multiple).addClass('party');
a selector is a string when passed to the $() fn. returns a collection of Elements that match the selector. So there is nothing wrong with this code.
Your code can also be written as,
var object1 = "#object1",
object2 = "#object2";
$(object1).add(object2).doSomething();
or it can be further optimized as,
var object1 = $('#object1'),
object2 = $('#object2');
object1.add(object2).doSomething();
where doSomething can be a jQuery or jQuery plugin defined method.
Why don't you use the easy way.
var severalVar = 'h1,h2,h3,h4,h5,h6';
$(severalVar).hide()

Categories

Resources