开发者

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 开发者_JAVA百科do involves Javascript and i'm only a beginner!

Please be detailed when explaining!! Thanks =3


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜