简体   繁体   中英

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 to do involves Javascript and i'm only a beginner!

Please be detailed when explaining!! Thanks =3

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.

DEMO

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);
  • 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

<div id="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 1
var html = divs[1].outerHTML;
html += divs[2].outerHTML;
html += divs[0].outerHTML;
html += divs[4].outerHTML;

el.innerHTML = html;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM