user2401882
user2401882

Reputation: 15

Appending content to every other div

This is simple but I got stuck and need some fresh mind for help.

What I want to achieve is to append content with jQuery to div. But to another div every other time, like this:

I have js now that it appends every 30 seconds content. HTML is like this:

<div class="wrapper">
    <div class="a"></div>
    <div class="b"></div>
</div>

So every other time I would like it to add div b and every other time to div a.

Sorry for bad explanation.

Upvotes: 0

Views: 95

Answers (4)

Akxe
Akxe

Reputation: 323

Pure js version that cycle thought all divs in wrapper and add to its content. If you ever wanted to have more of those divs.

var divToAddTo = getElementById('warper').getElementsByTagName('div');
setInterval(function(){
    divToAddTo[i].innerHTML+="your content";
    i++;
    if(i=>divToAddTo.lenght){
        i=0;
    }
},30000);

Upvotes: 1

Bez Hermoso
Bez Hermoso

Reputation: 1132

Try

var $wrapper = $('.wrapper');
var container1 = $('.wrapper .a');
var container2 = $('.wrapper .b');

setInterval(function(){

    var content = 'Hello, world!';

    var container = $wrapper.data('nextContainer');

    if(container == null)
         container = container1;

    container.append(content);

    $wrapper.data('nextContainer', container == container1 ? container2 : container1 );


}, 30 * 1000);

Upvotes: 0

Vond Ritz
Vond Ritz

Reputation: 2012

Here's the FIDDLE

setInterval(addDiv, 10000);
var aOrB = "a";

function addDiv() {
    $('#wrapper').append("<div class=" + aOrB + ">This is div with class " + aOrB + "</div>");
    if (aOrB === "a") aOrB = "b";
    else aOrB = "a";
}

Upvotes: 3

Karlen Kishmiryan
Karlen Kishmiryan

Reputation: 7522

You can use setInterval and appendTo functions to achieve this. Here is the JSFiddle. Check it out. Or if you have an array with fixed values, you can use it like this to use every item as a class of new div. Here is the JSFiddle for it.

Upvotes: 0

Related Questions