I have a query ajax response which I then use to set the array variables. Is there anyway to use a 'For Loop' to change to #name so that I don't have to write out a line of code to set each array element.
array[0]=$('#event00',response).html();
array[1]=$('#event01',response).html();
array[2]=$('#event02',response).html();
array[3]=$('#event03',response).html();
So '#event00' could be used in a for loop to change to '#event01' etc
You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects. If you are using jQuery you can use either the $. each() method or a for loop to iterate through an array.
jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.
JavaScript for loop start with first statement. The loop starts in position 0 ( let i = 0 ) . The loop automatically increments i for each run. The loop runs as long as i < array.
A for...of loop operates on the values sourced from an iterable one by one in sequential order. Each operation of the loop on a value is called an iteration, and the loop is said to iterate over the iterable. Each iteration executes statements that may refer to the current sequence value.
Use a regular for loop and format the index to be used in the selector.
var array = [];
for (var i = 0; i < 4; i++) {
var selector = '' + i;
if (selector.length == 1)
selector = '0' + selector;
selector = '#event' + selector;
array.push($(selector, response).html());
}
What about something like this?
var arr = [];
$('[id^=event]', response).each(function(){
arr.push($(this).html());
});
The [attr^=selector]
selector matches elements on which the attr
attribute starts with the given string, that way you don't care about the numbers after "event".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With