Reputation: 15
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
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
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
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