Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change div order in CSS or javascript

say I have layout like so:

<div id="main">            
    <div id="NormalContent">
        {some content which is a fixed length list}
    </div>
    <div id="FeaturedContent">
        {some content which may contain a long list}
    </div>
</div>

and I want to place FeaturedContent above NormalContent.

Can I do this with CSS? I assume I can with Javascript?

like image 668
Sam Holder Avatar asked Jan 15 '11 12:01

Sam Holder


People also ask

Should I write CSS or JavaScript first?

Once you've mastered those two languages, you can move on to learning JavaScript. Not only will that give you a better foundation on which to build your web development skills, but learning HTML and CSS first will also make it easier to understand JavaScript when you do eventually start learning it.

How do I change the order of responsive CSS?

CSS Flexbox allows you to change the order of elements without changing the HTML markup. So: Order the elements for desktop. Then use media queries and flex display to change the order.

How do I change my Dom order?

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 .

How do you change a div?

If you need to completely replace the HTML content of the div , use the innerHTML property. Copied! const div = document. getElementById('container'); // ✅ Change (replace) the text with HTML div.


2 Answers

For a non-jquery answer

var content = document.getElementById('FeaturedContent');
var parent = content.parentNode;
parent.insertBefore(content, parent.firstChild);

Note that there is no need to remove it from the DOM, adding it a second time will move it.

like image 115
Hemlock Avatar answered Oct 03 '22 22:10

Hemlock


this is a clearer way to move them with 1 line of jQuery:

$('#FeaturedContent').prependTo('#main');
like image 34
davin Avatar answered Oct 03 '22 22:10

davin