Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript /jQuery - For Loop

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

like image 465
user1216855 Avatar asked Feb 29 '12 20:02

user1216855


People also ask

Can I use for loop in jQuery?

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.

How do I iterate through a div in jQuery?

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.

How does a for loop start in JavaScript?

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.

What is for of loop in JavaScript?

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.


2 Answers

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());
}
like image 200
Greg Avatar answered Oct 17 '22 10:10

Greg


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".

like image 28
julioolvr Avatar answered Oct 17 '22 10:10

julioolvr