简体   繁体   中英

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.

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
});

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM