What is some Javascript code that will allow me to list out the id names of my divs and then display them in that order without having to actually change the code on my page?
I don't want to just swap two divs at a time to do this, I want a list/array that I can type the order into and it will show in that order.
I have 4 divs (div1开发者_JAVA百科, div2, div3, div4)
Thanks =D
Assuming HTML like this
<div id="wrapper">
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<div id="four">Four</div>
</div>
You could do this with jQuery
var w = $('#wrapper').html();
var arr = w.split('\n');
$('#wrapper').html(arr[2] + arr[4] + arr[1] + arr[3]);
Changing the order of the array elements as necessary.
NB: I am splitting the html into an array based on the line break \n
. It gives a first blank line, as I am collecting from the start of div#wrapper
. Therefore arr[0]
is never used.
Example: http://jsfiddle.net/jasongennaro/yFEVz/1/
Here is a basic Dom element sort. The only JQuery I use here is to collect all the elements within the container and push them to an array. You can remove the jquery, but you would have to convert the nodeList to an array for the sort to work. Cheers!
When doing operations like this using as little JQuery as possible, as well as manipulating/accessing the DOM as little as possible will greatly improve execution time.
http://jsfiddle.net/rlemon/wATVf/
Give the elements in question ('your divs') a common class and use that to manipulate them as a group -- with jQuery, the code to do so would look something like this:
$('.my-divs').each(function (idx, val) {
// sort your elements here;
// use something like $(val).is('#your-id') to inspect their id.
});
... assuming the HTML for your divs looks something like this:
<div id="div1" class="my-divs"> ... </div>
<div id="div2" class="my-divs"> ... </div>
<div id="div3" class="my-divs"> ... </div>
<!-- et cetera -->
精彩评论