This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed last year.
I have multiple in my code, each with class="output" and unique IDs.
<p>Workers: <span class="output" id="workersOutput">0</span><span class="output" id="workersProdOutput"></span></p>
I want to use querySelectorAll to get them addressable in js via variables/const so that I can change their values with textContent.
Individually, I would do the following to find each div, and then the second line to update it on screen.
const workersOutput = document.getElementById('workersOutput');
workersOutput.textContent = `${workers}`;
This is really messy though when I'll have many of these to do (12 at the moment, more to come).
Using querySelectorAll, I can make some hybrid version, using their individual index numbers from the node list. It's not exactly readable or easy to use, as the data attached to each is only visible if I output it somewhere. Not to mentioned if I add more divs, those numbers will change and not be assigned to the same IDs anymore.
const outputs = document.querySelectorAll('.output');
outputs[2].textContent = `${workers}`;
Couldn't I use maybe forEach to create a variable for each using the ID attached to that index number? Or something along the lines of the below example (I know that's not how that works, but I want to get the idea across):
const outputs = document.querySelectorAll('.output');
outputs.forEach((output) => {
const outputs[2] = document.getElementById(output.id);
});
I could also be way off on how to accomplish this the "right way", I'm newish to coding.
Use an object whose property names are the IDs.
const outputs = {};
document.querySelectorAll(".output").forEach(el => outputs[el.id] = el);
Related
This question already has answers here:
What is the most efficient way to create HTML elements using jQuery?
(12 answers)
Closed 7 years ago.
Is there any significant difference in how the new DOM element is created? Are there any advantages/disadvantages of using one way over another or does it come down to personal preference? I usually use the first way and only recently found out about the second one.
var test1 = $('div#test1'),
test2 = $('div#test2')
;
// first way
$('<div/>')
.addClass('mainClass subClass')
.attr('id', 'someId2')
.attr('data-extra', 'extraInfo')
.text('some text')
.appendTo(test2)
;
// second way
$('<div/>',
{
'class': 'mainClass subClass',
'id': 'someId1',
'data-extra': 'extraInfo',
'text': 'some text'
})
.appendTo(test1)
;
I think different ways are differ in performance , put not completely sure the from the perfect answer
i am using pure javascript
var element = document.createElement("div");
var elementContent = document.createTextNode("My div");
element.appendChild(elementContent);
// add div to body
document.body.appendChild(element);
Second example will be faster compared to first.
In case of first. The object is created and returned. And then you are using jquery methods which gets the jquery object of element everytime and sets the new classes/attributes.
In case of second approach, it iterate over the collection of properties to create the dom element along with those attributes and classes.
This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow
I don't think the answer of this problem is very difficult but I just can't get it to work!
I have this div where answers are stored like ("A""B""C") etc. I am reading this div with jQuery so I can calculate the score, so far so good.
Because I need to get each answer individually I am splitting the answers like this:
var totalAnswer = $(correctAnswer.split(/A/g).length - 1);
Above I calculate the "A" answers and count them.
The problem is that it returns it like this:
[3] instead of just 3 without the []. Is there a way I can remove the brackets?
No idea why you're wrapping with jquery object. I'd say you just need to replace
var totalAnswer = $(correctAnswer.split(/A/g).length - 1);
by
var totalAnswer = correctAnswer.split(/A/g).length - 1;
I have a for loop that cycles through the number of elements that the user has created. There are a lot of available settings in this plugin, and each element can receive it's specific settings.
User settings are entered in the following format: speed_x: "1000,500 > 1000,200 > 0,0"
This controls the speed_x in/out for 3 separate elements. The > divides by object and the commas separate the in/out.
So I can grab specific object speed_x values, I've split speed_x into speed_x_set (splitting by >) resulting in:
1 1000,500
2 1000,200
3 0,0`
3 Inside the loop, I grab the value by index (since it's the object #) and split it by comma (to get speed_x_in and speed_x_out.)
for(var i=0; i<OS.numberofobjects; ++i){
OS.speed_x_on_set[i]=speed_x_set[i].split(",")[0],
OS.speed_x_off_set[i]=speed_x_set[i].split(",")[1],
...
};
Everything is assigned by object and by setting in/out correctly into the master OS settings object. T*he problem is I have many, many settings which need to be split in this fashion...* for example: delay_x_set, speed_y_set, opacity_set, etc. Their names are all based on the default setting name, with "_set" added as shown above. Hopefully this provides enough information. Thanks!
I would avoid to access to the same item twice and perform the same split twice for each iteration. So, you could have something like:
for (var i = 0, item; item = speed_x_set[i++];) {
var values = item.split(",");
OS.speed_x_on_set.push(values[0]);
OS.speed_x_off_set.push(values[1]);
}
Notice that in JavaScript 1.7 (Firefox) you can simply have:
for (var i = 0, item; item = speed_x_set[i++];) {
var [on, off] = item.split(",");
OS.speed_x_on_set.push(on);
OS.speed_x_off_set.push(off);
}
And hopefully in the next version of ECMAScript as well.
It's called "destructuring assignment".
I would say to cache the split result
for(var objindex=0; objindex<OS.numberofobjects; ++objindex){
var splits = speed_x_set[objindex].split(","); //Cache the split so its does not need to be done twice
OS.speed_x_on_set[objindex] = splits[0];
OS.speed_x_off_set[objindex] = splits[1];
...
};
What you're looking for is called parallel assignment, but unfortunately, JavaScript doesn't have it.
In ruby, however, it is common to see similar patterns:
first, second = "first second".split
As others have noted, the obvious way would be to cache split results and assign them separately. Sorry for not answering your question directly.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Use javascript variable in object name
I am using CKeditor as a rich text editor. I have dynamically generated textareas with a unique ID that need replacing with text editors. That is working fine, but I then need to call getData(); on the textarea to get the data for an AJAX call. This is easy enough:
var editor_data = CKEDITOR.instances.editor1.getData();
The problem is I need editor1 to be dynamic, depending on the value of an attribute on a button. I record the textarea's identifier in a sibling button's name attribute:
var INSTANCE_NAME = $(this).attr('name');
Logging that out I get the correct editor ID back. (Note only using CAPS to highlight where it needs to be used in the next code block.)
I now need to use that INSTANCE_NAME as a variable like so:
var editor_data = CKEDITOR.instances.INSTANCE_NAME.getData();
I imagine my entire code needs to look something like this:
var INSTANCE_NAME = $(this).attr('name');
var editor_data = CKEDITOR.instances.INSTANCE_NAME.getData();
But I just get an error that CKEDITOR.instances.INSTANCE_NAME is undefined (which isn't surprising really)
Thanks
There are two ways to access properties in an object:
object.property
object['property']
Because the second option takes the property name as a string, you can build it dynamically — in this case, using the string INSTANCE_NAME:
var INSTANCE_NAME = $(this).attr('name');
var editor_data = CKEDITOR.instances[INSTANCE_NAME].getData();
// \_____________/
// ^
Use square brackets:
var editor_data = CKEDITOR.instances[INSTANCE_NAME].getData();