How can I do this
<div>
<p>A</p>
<p>B</p>
<p>C</p>
</div>
What I expected to be the results
C
B
A
How can I achieve this?
How can I do this
<div>
<p>A</p>
<p>B</p>
<p>C</p>
</div>
What I expected to be the results
C
B
A
How can I achieve this?
You can order the items in reverse, by specifying flex
display.
div {
display: flex;
flex-direction: column-reverse;
}
<div>
<p>A</p>
<p>B</p>
<p>C</p>
</div>
Alternatively, you could transform the child elements by flipping them across their directional axis. Flip the entire div
and then flip each p
inside the div. Although this works, it should be avoided in favor of flex
. Note: After transforming the elements, selection will become very wonky.
div, p {
transform: scale(1, -1);
}
<div>
<p>A</p>
<p>B</p>
<p>C</p>
</div>
You could also do this in JavaScript using a function that iterates though a Node's childNodes
and inserts them before the first child.
/**
* @describe Reverses the child nodes of a node in-place.
* @param {Node} node - The parent of the child nodes to be reversed
*/
const reverseChildNodes = node => {
for (let i = 1; i < node.childNodes.length; i++) {
node.insertBefore(node.childNodes[i], node.firstChild);
}
}
if (Element.prototype.reverseChildren === undefined) {
Element.prototype.reverseChildren = function() {
reverseChildNodes(this);
};
}
// Global function
reverseChildNodes(document.querySelector('.section:first-child'));
// Prototype method on Node object
[...document.querySelectorAll('.section')].pop().reverseChildren();
.section { border: thin solid grey; margin: 0.25em; padding: 0.25em; }
<div class="section">
<p>A</p>
<p>B</p>
<p>C</p>
</div>
<div class="section">
<p>A</p>
<p>B</p>
<p>C</p>
</div>
Use flexbox :
.wrapper{
display :flex;
flex-direction: column-reverse;
}
<div class='wrapper'>
<p>A</p>
<p>B</p>
<p>C</p>
</div>