Is there a way to increase the z-index of the matching element by 1, without iteration?

I need to increase z-index by 1, out of all span with class .page . In any case, there can be more than 100 agreed elements (no more than 150 in any case). Now I repeat each of them and change the z-index to the following code.

  $('#mydiv span.page').each(function() { var zi = parseInt($(this).css('z-index')) + 1; $(this).css('z-index', zi); }); 

Is there a better way to handle this for better performance. I am using jQuery.

+6
source share
3 answers

The best way would be to rewrite your logic so as not to depend on a uniform incremental z-index in element styling. If you ever execute this logic once, perhaps you can set up some general CSS rules that simply include going to the class to achieve the desired layout. Assuming this is not an option, you cannot make it more efficient.

You can temporarily disable the '#mydiv' element to reduce page redrawing, but it’s hard to get extra help without additional information, and this can confuse other things.

 var div = $('#mydiv'); var prev = div.prev(); div.detach(); // You can clean up your jQuery like this: div.find('span.page').css('z-index', function(index, zIndex) { return parseInt(zIndex, 10) + 1; }); div.insertAfter(prev); 
+2
source

Some kind of tricky way:

Create new style

 var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '.cssClass { z-index: value; }'; document.getElementsByTagName('head')[0].appendChild(style); document.getElementById('yourElementId').className = 'cssClass'; 
+3
source

In terms of performance, @Jaykishan Mehta is one the best, then the for loop comes.

 for (var i = 0, spans = document.querySelectorAll('#mydiv span.page'), len = spans.length; i < len; i += 1) { spans[i].style.zIndex = parseInt(spans[i].style.zIndex, 10) + 1; } 

Using jQuery is massive, i.e. for each iteration, etc., can slow down globally.

I mean, jQuery can perform individual tasks pretty quickly, but the amount can cause a general slowdown.

It all depends on your application / website.

+1
source

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


All Articles