How can I manipulate elements without recounting the layout using jQuery

I have many div elements where I need to recount their heights. Divas are inside another div with id = "content".

I am using jQuery as follows:

$("#content div").css("height", "*=" + Math.random()); 

There are about 1000 divs that are recounted like this. This takes some time, and I understand that this is because the layout is recounted once for each element. It only takes a few seconds, but this is a significant method.

I came up with tips on using document fragments that are just plain JavaScript. I would like to use jQuery for this.

Is there a way, using jQuery, to separate these divs and manipulate them outside the active DOM before writing them so that the layout is not recounted until I finish the manipulation?

+6
source share
1 answer

Try using detach Something like the following:

HTML

 <div id="content" > <div class="test" style="height:100px;"> </div> <div class="test" style="height:100px;"> </div> <div class="test" style="height:100px;"> </div> <div class="test" style="height:100px;"> </div> <div class="test" style="height:100px;"> </div> 

jQuery

 var el = $('.test').detach(); el.each(function(index){ var height = $(this).attr('style').substring($(this).attr('style').indexOf('height:')+7,$(this).attr('style').indexOf('px')); $(this).attr('style','height:'+height*Math.random()+'px'); }); $('#content').append(el); 

I was not able to manipulate height on individual elements. I found one way to do this, although if you have a height in the style attribute, you can pull the information out and manipulate it.

Here is an example, I hope it will be useful to you.

http://jsfiddle.net/4Sb8T/

+2
source

Source: https://habr.com/ru/post/957383/


All Articles