Kald
Kald

Reputation: 48

Looping through objects in an array JS

I'm putting together this script which pulls two child elements from a containing div #mini_ads, adds them to an array. I want to be able to use the array to select them via index in order to manip. them individually.

I know I can just select them w/o even using an array of course, but I want this array as I may add multiple more elements later.

The issue is that I am not able to select the items individually by their index in the array. The current script I've got going is selecting and manipulating both objects in the array as if they're both index[0].

var miniAds = $('#mini_ads');
var elements = miniAds.children();
var changeWtime;
var adsArr = new Array();
var i = 0;
var x = 0;
adsArr.push(elements);
console.log(adsArr);
adsArr[i].css("display", "none");   
var changeWtime = setInterval(function () {
    for (x; x < 1; x++) {
        return x;
        while (x > i) {
            adsArr[1].css("display", "block");
        }
    };
}, 5000);
console.log(x);
changeWtime;

I am not sure where I'm going wrong here. Assistance will be much appreciated. Thanks in advance.

Upvotes: 0

Views: 169

Answers (3)

hitautodestruct
hitautodestruct

Reputation: 20852

Issues with your code

  • You're creating a double array when you push elements into 'adsArr':

    adsArr.push(elements);
    
  • You're throwing a return statement in the for loop:

    for (x; x < 1; x++ ){
        return x;
        // ...
    
  • You have a double loop for no reason while inside of the for.

Solution

I was going to explain the solution to this verbally, but after coding an example I realized that there is too much to explain this is another solution similar to yours:

var miniAds = $('#mini_ads'),
    elements = miniAds.children(),
    i = 2,
    x = 0;

elements.hide();

var changeWtime = setInterval(function () {
  if ( x < i ) {
      $(elements[x]).show();
  }

  x++;
}, 5000);

Link to example on jsbin.

Upvotes: 3

Annie
Annie

Reputation: 81

In plain Javascript use .styles()

.css() which is a JQuery method but not Javascript

ref http://www.w3schools.com/js/js_htmldom_css.asp

Upvotes: 1

codebreaker
codebreaker

Reputation: 1485

Hi u should push child divs as below function does and after that i believe u can perform ur task...

var adsArr= [];

$('#mini_ads').children().each(
    function(i){
        adsArr.push(this);
    });

Upvotes: 1

Related Questions