Question

i have div's that arrange like this:

<div id='div1' style='z-index:50'>1<div>
<div id='div2' style='z-index:200'>2<div>
<div id='div3' style='z-index:60'>3<div>
<div id='div4' style='z-index:100'>4<div>

i am taring to Rearrange z-index with jquery like this:

<div id='div1' style='z-index:1'>1<div>
<div id='div2' style='z-index:4'>2<div>
<div id='div3' style='z-index:2'>3<div>
<div id='div4' style='z-index:3'>4<div>

somebody have any idea how can i do this

thank in adv yoav

Was it helpful?

Solution

You'd do that by getting the elements, sorting the collection by z-index, and then iterate and use the index to set the new z-index. This does not affect the elements position in the DOM, we're only rearranging the collection.

$('[id^="div"]').sort(function(a, b) {
    return a.style.zIndex - b.style.zIndex;
}).css('z-index', function(i) {return i+1;});

FIDDLE

Note that you have to close the DIV elements to make this work

OTHER TIPS

You can normally use jQuery's .css(); function, but since your style is directly in the HTML it won't overwrite it. You can use .attr():

For example:

$('#div1').attr('style','z-index:1');

You can do this 4 times if needed, and enter your own values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top