0

I am stuck in a problem where I have to re-arrange div's inside a div.

This html is in ajax response. There are accordions inside div with IDs like accordion 0 accordion 1 ,.... accordion 4.

How can I re-arrange these divs using javascript?

function GetHtmlUsingAjax() {
  fetch(url)
    .then((response) => {
      return response.text();
    })
    .then((result) => { // result here contains the html given above
      //how can i re-arrange their order using javascript as div0,1,2,3..
    });
}
<div id="maindiv">
  <div id="sudiv0">
    <div id="accordion0">
    </div>
  </div>
  <div id="sudiv2">
    <div id="accordion2">
    </div>
  </div>
  <div id="sudiv1">
    <div id="accordion1">
    </div>
  </div>
  <div id="sudiv3">
    <div id="accordion3">
    </div>
  </div>
</div>

5
  • hi @connexo , I know accordion is not a tag ,but can we re-arrange div taking something else inside instead of accordion Commented Feb 20, 2021 at 9:34
  • let me edit this html a little. Commented Feb 20, 2021 at 9:35
  • Your snippet still has the script tags in it in the JS section. If you remove them your JS error goes away. Please show us the code of anything you have tried already. Commented Feb 20, 2021 at 9:37
  • hi @connexo , I have edited html . Commented Feb 20, 2021 at 9:38
  • hi @AHaworth , this code is just for getting an idea Commented Feb 20, 2021 at 9:41

1 Answer 1

1

Like this

PS DIVs do not have values

const container = document.getElementById("container"); // or use a fragment
// container.innerHTML = response.text();
// demo string, remove when using the response
container.innerHTML = `<div id="maindiv">
  <div id="sudiv0">
    <div id="accordion0">accordion 0</div>
  </div>
  <div id="sudiv2">
    <div id="accordion2">accordion 2</div>
  </div>
  <div id="sudiv1">
    <div id="accordion1">accordion 1</div>
  </div>
  <div id="sudiv3">
    <div id="accordion3">accordion 3</div>
  </div>
</div>`

const main = document.getElementById("maindiv");
[...document.querySelectorAll("[id^=sudiv]")]
  .sort((a,b) => a.id.replace("sudiv","") - b.id.replace("sudiv",""))
  .forEach(div => main.appendChild(div))
<div id="container"></div>

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

3 Comments

hi @mplungjan , here in this statement while creating an array [...document.querySelectorAll("[id^=sudiv]")] , I wanted to use the response html after fetching api. what should i use in place of "document" ?
Do I have to use this querySelector after inserting response html to page? Or before rendering to page?
I suggest you render but you can use a fragment too. See update

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.