0

I have something like this:

<div class="list-group list">
    <a href="blabla" id="1" data-order="1">Hello</a>
    <a href="blabld" id="2" data-order="2">World</a>
</div>

No I try to change the order of the links dynamically with plain Javascript.

Does anyone have any suggestion, how to do so?

My Goal is this:

<div class="list-group list">
    <a href="blabld" id="2" data-order="1">World</a>
    <a href="blabla" id="1" data-order="2">Hello</a>
</div>
2
  • possible duplicate of How I can change child elements order in JS? Commented Sep 14, 2015 at 13:15
  • Oh, wait, plain JS and not jQuery... Sorry, not a duplicate. How do I unflag? Commented Sep 14, 2015 at 13:16

3 Answers 3

1

Here you go:

function sort(r) {
    var $list = document.getElementsByClassName('list')[0];
    var listGroupA = document.getElementsByTagName('a');
    var $listGroupA = [];
    for (var i = 0; i < listGroupA.length; ++i) {
        $listGroupA.push(listGroupA[i]);
    }
    $listGroupA.sort(function (a, b) {

        return r * (a.getAttribute('data-order') - b.getAttribute('data-order'));

    });
    for (var i = 0; i < $listGroupA.length; i++) {
        $list.removeChild($listGroupA[i]);
    }
    for (var i = 0; i < $listGroupA.length; i++) {
        $list.appendChild($listGroupA[i]);
    }
}
var reverse = 1;
$('#sort').click(function () {

    reverse = reverse * -1;
    sort(reverse);
});

And fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

You can delete the last list item and create one more item and append it to the container div like this :

var world = document.getElementById("2");
var id = world.id;
var data = world.getAttribute("data-order");
var div = document.getElementsByClassName("list")[0];

div.removeChild(world);
var newA = document.createElement("a");
div.appendChild(newA);
newA.id = id;
newA.dataset.order = data;

Comments

0

JSFiddle Example

Reorder = function()
{    
  var x = document.getElementsByTagName('a');
  document.getElementsByClassName('list').innerHTML = "";
  var content  =  "";
      for(i = x.length; i > 0; i--)
      {
          content = content + x[i - 1].outerHTML;
      }
  document.getElementsByClassName('list').innerHTML = content;
}

The above code will take the existing items into an array and clear the contents. Now, they will be added to the div. I've used the classname here to add it to the div.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.