How would I go about reordering divs without altering the HTML source code?
example, I want divs to appear in order #div2, #div1, #div3, but in the HTML they are:
<div id="#div1"></div> <div id="#div2"></div> <div id="#div3"></div>
Thanks!
To change the order of HTML elements with JavaScript, we can use some native JavaScript DOM manipulation functions. We create the reorder function to reorder the elements. To do this, we create a new document fragment to hold the new content with document. createDocumentFragment .
Block level elements arrange elements within a page flow Vertically (from top to bottom) and in-line element simply flow horizontally (from left to right) within their container box. The official term for this normal position is called Normal Flow .
You can do it using flexbox. According to csstricks: The order property is a sub-property of the Flexible Box Layout module. Flex items are displayed in the same order as they appear in the source document by default.
There is no catch-all way of reordering elements with css.
You can inverse their order horizontally by floating them all to the right. Or you can position them absolutely relative to the body or some other containing element - but that comes with severe limitations regarding the size of the elements, and positioning relative to other elements on the page.
Short answer: You can only achieve this in a very limited set of circumstances. Reordering elements is best done in markup.
If you have no control over the html, you could use javascript. Here using jQuery:
$("#div2").insertAfter("#div3"); $("#div1").prependTo("#div2");
I certainly don't recommend that unless your hands are tied. It will be harder to maintain, and for your end users it will make your page "jerk around" while its setting up the page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With