How Could I Make Javascript Reorder My Div Tags?
Lets say i have 4 divs (with id='div1' 'div2' etc) How could I use Javascript to make it re-order to 2,3,1,4? Please don't suggust to use anything else... because what i'm trying t
Solution 1:
You can insert an element before an other by calling the insertBefore()
function on the parent element.
For example if you want to insert div2 before div1, you can do this:
parent.insertBefore(div2, div1);
The following code inserts div1 before div4:
var div1 = document.getElementById('div1');
var div4 = document.getElementById('div4');
var parent = div1.parentNode;
parent.insertBefore(div1, div4);
After executing the the order of the divs is 2, 3, 1, 4.
Solution 2:
This should be pretty easy to understand:
HTML:
<div id="container">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
</div>
Javascript:
var container = document.getElementById('container'),
divs = container.getElementsByTagName('div'),
tmpdiv = document.createElement('div'),
order = [2, 1, 3, 4];
for (var i = 0; i < order.length; i++) {
tmpdiv.appendChild( document.getElementById('div' + order[i]) );
}
container.parentNode.replaceChild(tmpdiv, container);
Solution 3:
- I'm grabbing the DIV with id container, using getElementById
- Getting the children of that DIV with
.children()
- using outerHTML and building a new string swapping the 1st and 3rd elements
- setting the innerHTML to the string i just built
HTML
<divid="containter"><div>1</div><div>2</div><div>3</div><div>4</div></div>
JavaScript
var el = document.getElementById('containter'),
divs = el.children,
len = divs.length;
// swap 3 and 1var html = divs[1].outerHTML;
html += divs[2].outerHTML;
html += divs[0].outerHTML;
html += divs[4].outerHTML;
el.innerHTML = html;
Post a Comment for "How Could I Make Javascript Reorder My Div Tags?"