Arry
Arry

Reputation: 15

Make multiple divs with same class work at same time through javascript function

I have two divs with same class name:

<div class="bubble" style="margin-bottom: 160px">
        <p>bubble1</p>
    </div>
    <div class="bubble">
        <p>bubble2</p>
    </div>
</div>

How can i apply javascript so that both of them works simultaneously. Right now only the first one works and nothing happens on the second one.

Upvotes: 0

Views: 835

Answers (3)

Footer
Footer

Reputation: 139

var x=document.getElementsByClassName('bubble');

//now x is an array of all elements with the class bubble

for(i=0;i<=x.length-1;i++){
    //Do operations accordingly
}

Upvotes: 0

Adam Azad
Adam Azad

Reputation: 11297

There is no true simultaneous operations in JavaScript. Yet, each operation or iteration happens in milliseconds, close enough. You can loop over the matches.

var bubbles = document.querySelectorAll('.bubble'); // get all divs with class bubble

[].forEach.call(bubbles, function(bubble){
    // do something to bubble
});

Upvotes: 3

Obie
Obie

Reputation: 302

You can use the following code to achieve what you wanted.

var bubbles = document.querySelectorAll('.bubble');
for(var i=0; bubbles[i]; i++){
    var bubble =  bubbles[i];
    // now you do whatever you want to do with bubble 
    // i.e bubble.style.marginLeft = "10px";
}

Or you can just use jQuery to do the same. Its just one line code

$('.bubble').css({marginLeft:10});

Thanks

Upvotes: 0

Related Questions