-1

i have a html Page with a specific order, for instance:

    <div id="three"></div>
    <div id="two"></div>
   <div id="one"></div>

But i need order it, i can touch the html, so, the idea is use Javascript/Jquery to do that, is there a way to make that without touch the html?

Aletz Morgan
  • 290
  • 1
  • 3
  • 13

3 Answers3

3

for the simple answer using .before:

$('#three').before('#two');
$('#two').before('#one');
Evan
  • 5,975
  • 8
  • 34
  • 63
2

with jQuery:

$('#one').parent().append($('#three')).append($('#one')).append('#two');

this way you have, div 3, 1, 2 in that order.
You are selecting one of the divs, and selecting it's parent. then you append them at the order you want.

if you want to use pure javascript:

var parent = document.getElementById('one').parentNode;
parent.appendChild(document.getElementById('three'));
parent.appendChild(document.getElementById('one'));
parent.appendChild(document.getElementById('two'));

now, assuming you have a lot of divs, i will assume #one til #ten:
you can create an array, with the ids ordered as you wish, for example:

var order = ['ten', 'eight', 'six', 'four', 'two', 'nine', 'seven', 'five', 'three', 'one'];
for(var i = 0; i < order.length; i++){
    parent.appendChild(document.getElementById(order[i]));
}

is this what you're looking for?

André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120
  • thx for the answer it works, but in my case also i have some more divs ex:
    three
    two
    one
    test
    tests
    testes
    All of them are created in asp and parse in the html, the asp some time sends unordered items, so i dont know the exactly position of them, if i use the parent() to set the position some time it not will be in the correct position
    – Aletz Morgan Jan 27 '12 at 23:12
  • so, you want an easyway to order them all? – André Alçada Padez Jan 27 '12 at 23:13
  • no, parent refers to the container of those divs. can be another div or can be the body, for example – André Alçada Padez Jan 27 '12 at 23:17
  • 1
    Little note, you need an extra closing parenthesis here: `parent.appendChild(document.getElementById(order[i]‸);` – Jordan Gray Jan 27 '12 at 23:45
1

yes... try to use this code:

$('#two').appendTo($('#one').parent())
$('#three').appendTo($('#two').parent())
Mattia Larentis
  • 192
  • 1
  • 9