How to make a variable which consists of multiple 'divs' - javascript

I have a question regarding variables in Javascript.
When I assign a var to a ID I do it like this:
var x = document.getElementById("div_name");
But I would like to make a variable which consists of multiple 'divs'.
I thought this might work but I does not:
var x = document.getElementById("div_name"),document.getElementById("div_name2");
Can someone please help me find the right code syntax and explain why the syntax I tried is incorrect.

So, If you just want them as a list of div's you could do this:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
Just wrap them up with [].

If your var should contain more than one object (div in your case), then you need to have more variable or, better, an array.
You can create yor array by using following code.
var x = [document.getElementById("div_name"), document.getElementById("div_name2")];
This is due to the fact that different DIVs in the DOM page are different objects...

There is no such variable that is defined as:
var x = somthing, somesthingElse
You need to chose a variable that can store a collection of "things". In your case the Array is an ideal choice:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
The brackets at the beginning and end of the expression are the syntax to declare a variable.

In addition to using Array, you can also store your divs in an Object
var divs = {
div1: document.getElementById("div_name"),
div2: document.getElementById("div_name2")
};
Thus, you could give a convenient name to your divs, but still pass them around as you please:
divs.div1;
divs.div2;
Or loop through them like so:
for (div in divs) {
console.log(divs[div]);
};

Related

Assign HTML elements ID to document.queryselector shorthand variables in a loop

I am new to Javascript development.
I am trying to assign HTML elements IDs stored in an array to shorthands to be used in my function later.
So that instead of writing :
let addprop = document.querySelector(`#addprop`);
let readprop = document.querySelector(`#readprop`);
let editprop = document.querySelector(`#editprop`);
let footer = document.querySelector(`#footer`);
let association = document.querySelector(`#association`);
I can attribute elements ids that i store in an array like this :
let arrayElements = ["addprop", "readprop", "editprop", "footer", "association"] ;
arrayElements.forEach(el => { return(new Function (`${el} = document.querySelector("#${el}");`)()); });
Now, this bit of code works but from what I read here :
Execute JavaScript code stored as a string
This is probably not a good way to do it and also declares global variables.
One problem I encountered is that if I try to directly execute the assignment like this :
el = document.querySelector(`#${el}`);
Then the el value takes the value of the named access ID element (https://html.spec.whatwg.org/multipage/window-object.html#named-access-on-the-window-object) and breaks the code.
So I resorted to generate a string first then execute it.
I could simply assign each shorthand manually but I spent way too much time trying to make this work and am now left curious as to what would be a good solution or approach for this.
And would the scope limitations for loops simply forbid me to do this without using global variables ?
edit : switched the working code in one line
Possible answer :
1 - does it matter to declare global variables like that ? As these variables already exist globally because of browsers named access for elements IDs.
2 - By kiranvj's answer, a solution can be to store in an object structured as keys being the shortcuts and the full strings being the values, and calling the shortcuts with the object[key] method ; or using destructuring to assign the values to variable directly with :
const {addprop, readprop, editprop, idfooter, assocpatients} = elements;
I feel like I am missing something on this last one but it also seems to work.
In the end I will stick with my first code as condensing the function in one line seems to negate the risks of cross site scripting (?), and global values for the variables assigned though this method anyway already exist because of named access.
You can create a dictionary with all the elements with ID and then destroy it into your variables, ignoring the unused ones.
function getAllElementsWithId() {
let elements = {}
for (let el of document.querySelectorAll('[id]')) {
if (!(el.id in elements)) {
elements[el.id] = el
}
}
return elements
}
let { addprop, readprop, editprop, footer, association } = getAllElementsWithId()
This uses document.querySelectorAll (link to MDN) to get all elements with an ID. Notice that for big pages this could be a performance issue.
Also, what you would usually do is to add them into a container, in this case it seems like a dictionary.
let arrayElements = ["addprop", "readprop", "editprop", "footer", "association"]
let elementsId = Object.fromEntries(arrayElements.map(id => [id, document.getElementById(id)]))
This uses Object.fromEntries (link to MDN) to generate the dictionary. Also I'm using document.getElementById (link to MDN) instead of document.querySelector so you don't need to add the hashtag before the id.
If you are concerned about global scope, you can try something like below. Use forEach instead of map . map also work but since you are not handling the return of map, forEach would be a better choice.
let arrayElements = ["addprop", "readprop", "editprop", "footer", "association"];
let elements = {};
arrayElements.forEach(el => elements[el] = document.querySelector(`#${el}`));
// access variables like elements.ID-NAME
console.log(elements);
<div id="addprop"></div>
<div id="readprop"></div>
Object destructing can be used if you know the object key name.
example : let {addprop} = element;
Another thing which you might be interested is Automatic global variables
This means a new variable (scoped to window) with the name of element id is created for all the elements in page. See the html5 spec. I would not recommend using it though.
So you don't have to call like document.querySelector('addprop')
addprop variable will have the DOM object.
See this example
// these works due to automatic global varaibles binding
alert(addprop);
console.log(addprop);
<div id="addprop">Some contents</div>

angularjs scope two values keeping pointing to each other

Hi I'm trying to copy a scope value from one to another scope. For example:
var items=$scope.order.invoicewindow.items;
$scope.order.orderwindow.items=items;
However right both scopes are pointing to each other. So if I change $scope.order.orderwindow = "abc", $scope.order.invoicewindow.items also becomes "abc" (which I don't want. I only want $scope.order.orderwindow = "abc").
Thanks
You can use angular.copy(source, [destination]);
var items= "YourValue";
angular.copy(items, $scope.order.invoicewindow.items);
$scope.order.invoicewindow.items = angular.copy(items); //Or You can also use this style

Javascript Computed Values With Arrays

Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']

Javascript: give a variable a name made of 2 variables

I want to create a new variable in javascript but it's name should made of a stale part and a variable one like this:
tab_counter = 1;
var editor + tab_counter = blabla
well i want the new variable name to be in this case editor1, is this possible?
You cannot create a stand-alone variable name that way (except as a global) (edit or except with eval()), but you can create an object property:
var tab_counter = 1;
var someObject = {};
someObject['editor' + tab_counter] = "bla bla";
You can create globals as "window" properties like that, but you probably shouldn't because global variables make kittens cry.
(Now, if you're really just indexing by an increasing counter, you might consider just using an array.)
edit also see #Birey's somewhat disturbing but completely correct observation that you can use "eval()" to do what you want.
It is possible
var tab_counter=1;
eval("var editor"+tab_counter+"='blah'")
alert(editor1);
eval("var editor"+tab_counter+1+";")
editor2='blahblah';
alert(editor2);
http://jsfiddle.net/5ZLYe/
You can do the eval method used by Birey or you can create a custom property of an object such as...
obj[editor + tab_counter] = blabla;
But it sounds like you're going about doing whatever you're doing in a particularly horrible way. If you just want to store multiple items which you can index into use an array...
var array = [];
array[0] = blabla;
array[1] = blabla2;
alert(array[0]); //shows value of blabla
alert(array[1]); //shows value of blabla2
It seems like you may want to consider using a Dictionary for something like this. This link which references this link describes your options there.

Help needed with Javascript Objects

I need some help with Javascript objects. This is what I've got:
_genre_id = {politics:'1',sport:'2',celeb:'3',gossip:'4',busi:'5'};
var genre = 'politics';
What I want to accomplish would be to simply get the value stored for politics, in this case 1 by doing something like this:
var genreID = _genre_id.genre;
But this of course doesn't work because the genre property doesn't exist. I want it to relate to _genre_id.politics.
Any ideas would be welcome.
How about _genre_id[genre]?
var _genre_id = {politics:'1',sport:'2',celeb:'3',gossip:'4',busi:'5'};
var genre = 'politics';
var genreID = _genre_id[genre];
Note that I added var before setting _genre_id, so that it gets declared in the current scope, without declaring it, you end up setting window._genre_id instead of a local variable.

Categories

Resources