Reputation: 158
I have code like this:
<div>
<div id="div1" class="flex">test 1</div>
<div id="div2" class="flex">test 2</div>
<div id="div3" class="flex">test 3</div>
<div id="div4" class="flex">test 4</div></div>
How to do something line that: when somebody clicks the div with "flex" class, this div go to the top of the "list". For example, if i click the div with id "div3" the order of elements should be: div3, div1, div2, div4.
I dont want to append the parent div or inner HTML.
Upvotes: 1
Views: 976
Reputation: 4125
You will need to add a div with id #first
before the divs, then use jQuery's insertAfter()
$(".flex").click(function() {
$(this).insertAfter( "#first" );
});
<div>
<div id="first"></div>
<div id="div1" class="flex">test 1</div>
<div id="div2" class="flex">test 2</div>
<div id="div3" class="flex">test 3</div>
<div id="div4" class="flex">test 4</div>
</div>
https://jsfiddle.net/joe_young/etgm865x/
Upvotes: 1
Reputation: 1892
Another solution without adding a new div
and using insertBefore().
Just given an id
to parent div
.
Inserting before the first child of the parent div
$(".flex").click(function() {
var element = document.getElementById('main').children[0];
if (!($(this)).is(element)) { //Checks if its first div or not
$(this).insertBefore(element);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="main">
<div id="div1" class="flex">test 1</div>
<div id="div2" class="flex">test 2</div>
<div id="div3" class="flex">test 3</div>
<div id="div4" class="flex">test 4</div>
</div>
Note: used jQuery 1.7.2
Upvotes: 0