Sorting DIVs inside other DIVs [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to sort divs according to their id using jQuery?
Well I'm having a really hard time trying to solve this and I actually had no sucess until now, I'm trying to sort DIVs inside Other DIVs by ID.
So here's how my DIVs are distribuited in my page
<div id="products" >
<div class="line">
<div id="Album2">[there are images and even other divs here in each Album]</div>
<div id="Album1"></div>
<div id="Album10"></div>
<div id="Album16"></div>
</div>
<div class="line">
<div id="Album9"></div>
<div id="Album3"></div>
<div id="Album4"></div>
<div id="Album7"></div>
</div>
<div class="line">
<div id="Album5"></div>
<div id="Album11"></div>
<div id="Album6"></div>
<div id="Album13"></div>
</div>
<div class="line">
<div id="Album8"></div>
<div id="Album14"></div>
<div id="Album12"></div>
<div id="Album15"></div>
</div>
</div>
and this should be my output:
<div id="products" >
<div class="line">
<div id="Album1"></div>
<div id="Album2"></div>
<div id="Album3"></div>
<div id="Album4"></div>
</div>
<div class="line">
<div id="Album5"></div>
<div id="Album6"></div>
<div id="Album7"></div>
<div id="Album8"></div>
</div>
<div class="line">
<div id="Album9"></div>
<div id="Album10"></div>
<div id="Album11"></div>
<div id="Album12"></div>
</div>
<div class="line">
<div id="Album13"></div>
<div id="Album14"></div>
<div id="Album15"></div>
<div id="Album16"></div>
</div>
</div>
But I have one more problem, all my products are listed and there are more than one page, I was actually able to track them and made a sorted Array of Strings but I didn't had the same luck doing it with the DIVs.
This is my page:
http://biscoitofino.jumpseller.com/catalogo
Any suggestions?
Thanks in advance.

Something like this should do it, at least within the context of a single page:
var lines = $("#products .line");
var elems = $("#products .line div");
for (var index = 1; index <= elems.length; index++) {
var elemId = "Album" + index;
var containerIndex = parseInt((index - 1) / 4);
var container = lines[containerIndex];
var elem = document.getElementById(elemId);
elem.parentNode.removeChild(elem);
container.appendChild(elem);
}
Here's an example: http://jsfiddle.net/dpHyn/
Although I think the real answer is, since presumably you've got a server that's providing the list of albums dynamically already, why not just have the server sort the elements properly when it loads them from the database (or whatever other datasource you are using)? That would save you all this trouble, and work properly with pagination as well.
​

var lines = $("#products > .line"),
albums = lines.children().toArray(),
line = -1;
albums.sort(function(a, b) {
return a.id.replace("Album", "") - b.id.replace("Album", "");
});
$.each(albums, function(i, el) {
if (!(i % lines.length))
line += 1;
lines.eq(line).append(el);
});
or without jquery
var lines = document.querySelectorAll("#products > .line"),
line = -1;
[].slice.call(document.querySelectorAll("#products > .line > div"))
.sort(function(a,b) {
return a.id.replace("Album", "") - b.id.replace("Album", "");
})
.forEach(function(el, i) {
if (!(i % lines.length))
line += 1;
lines[line].appendChild(el);
});

Related

remove any child element after certain div index by javascript or jquery

i have this html collection, i want if i click on any div class ".sday"
any other div that are present after that be remove .
for example if we click on sday 2 we should keep sday1 and sday 2, and 3 and 4 must delete
my script removing count is ok but it delete wrong div.
any idea?
<div id="parent" class="parent">
<div class="room-sheet">
<div class="sday">1</div>
</div>
<div class="room-sheet">
<div class="sday">2</div>
</div>
<div class="room-sheet">
<div class="sday">3</div>
</div>
<div class="room-sheet">
<div class="sday">4</div>
</div>
</div>
script(using jquery)
<script>
$(".sday").click(function(){
console.log("hello");
var parentElement = $(this).parent().parent().find('.room-sheet');
var parentChildernCount = $(this).parent().parent().find('.room-sheet').length;
var elementIndex = $(this).closest('.room-sheet').index();
var dd = parentChildernCount - elementIndex;
for(let i=elementIndex; i < dd; i++){
//note: make sure any element after our index in deleted!!!
$("#parent").find('.room-sheet').children().eq(i).remove();
}
})
</script>
Listen for clicks on a .sday on the parent, navigate to the parent of the clicked .sday (a .room-sheet), call nextAll to get all subsequent siblings, and .remove() them:
$('#parent').on('click', '.sday', function() {
$(this).parent().nextAll().remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent" class="parent">
<div class="room-sheet">
<div class="sday">1</div>
</div>
<div class="room-sheet">
<div class="sday">2</div>
</div>
<div class="room-sheet">
<div class="sday">3</div>
</div>
<div class="room-sheet">
<div class="sday">4</div>
</div>
</div>
Also, there's no need to require a big library like jQuery for something this simple, you may implement this with native DOM methods, if you like:
document.querySelector('#parent').addEventListener('click', ({ target }) => {
if (!target.matches('.sday')) {
return;
}
const sheet = target.parentElement;
while (sheet.nextSibling) {
sheet.nextSibling.remove();
}
});
<div id="parent" class="parent">
<div class="room-sheet">
<div class="sday">1</div>
</div>
<div class="room-sheet">
<div class="sday">2</div>
</div>
<div class="room-sheet">
<div class="sday">3</div>
</div>
<div class="room-sheet">
<div class="sday">4</div>
</div>
</div>
Save the current number and the maximum number in variables then just iterate through them, making sure not to delete the clicked one:
$(".sday").on("click", function() {
let start = parseInt($(this).text());
let finish = parseInt($(".sday").last().text());
for (let i = start + 1; i <= finish; i++) {
$(`.sday:conatins(${i})`).remove();
}
});

How to loop child divs parent by parent with respect to the horizontal level in jquery?

<div class="row">
<div class="parent">
<div class="child">child1</div>
<div class="child">child2</div>
<div class="child">child3</div>
</div>
<div class="parent">
<div class="child">child4</div>
<div class="child">child5</div>
<div class="child">child6</div>
</div>
<div class="parent">
<div class="child">child7</div>
<div class="child">child8</div>
<div class="child">child9</div>
</div>
<div class="parent">
<div class="child">child10</div>
<div class="child">child11</div>
<div class="child">child12</div>
</div>
<div class="parent">
<div class="child">child13</div>
<div class="child">child14</div>
<div class="child">child15</div>
</div>
<div class="parent">
<div class="child">child16</div>
<div class="child">child17</div>
<div class="child">child18</div>
</div>
</div>
I have sortable divs and i want to save the order of divs. But if i use jquery each function it loops parent divs and passing another parent after taking all childs of it vertically.What i am trying to do is getting child1,child4,child7,child10.. and so on. If we think this as a table i want to take values of cell row by row but jquery each doing this column by column.
The output that i want is 1,4,7,10,13,16,2,5,8,11,14,17,3,6,9,12,15,18
here is code in fiddle
Please check demo
var arr=[];
var count = $(".parent")[0].children.length;
for (var i = 0 ; i < count ; i++){
$(".parent").each(function(){
arr.push($(this.children[i]).text())
});
}
console.log(arr)
Please check this code made for you and let me know, If it's working for you or not.
var cnt = 0;
$(".parent:first-child .child").each(function () { cnt++; });
for (var i = 1; i <= cnt; i++) {
$(".parent").each(function () {
console.log($(this).children('.child:nth-child(' + i + ')').html());
});
}

Very strange javascript sorting values behaviour

I have been messing around with this for hours and the only thing I can narrow it down to is that if there is 14 elements to sort, it doesn't work properly, but if there is thirteen, it works fine.
I am trying to do a basic sort of DIV elements by the price values they hold inside.
Here is the simple html -
<div class="wrap">
<button id="numBnt">Numerical</button>
<div id="container">
<div class="box">
<h2>£10.35</h2>
</div>
<div class="box">
<h2>£21.35</h2>
</div>
<div class="box">
<h2>£21.35</h2>
</div>
<div class="box">
<h2>£102.35</h2>
</div>
<div class="box">
<h2>£10.35</h2>
</div>
<div class="box">
<h2>£10.35</h2>
</div>
<div class="box">
<h2>£10.95</h2>
</div>
<div class="box">
<h2>£100.35</h2>
</div>
<div class="box">
<h2>£100.05</h2>
</div>
<div class="box">
<h2>£200.00</h2>
</div>
<div class="box">
<h2>£5510.25</h2>
</div>
<div class="box">
<h2>£19.80</h2>
</div>
<div class="box">
<h2>£5510.25</h2>
</div>
<div class="box">
<h2>£510.25</h2>
</div>
</div>
</div>
And the javascript
var $divs = $("div.box");
$('#numBnt').on('click', function () {
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return parseFloat($(a).find("h2").text().replace(/£/g, '')) > parseFloat($(b).find("h2").text().replace(/£/g, ''));
});
$("#container").html(numericallyOrderedDivs);
});
With 13 div elements, the divs are sorted perfectly.
here is an example - http://jsfiddle.net/C2heg/380/
Then if I add another and make it 14 divs, the sort doesn't work correctly.
here is an example - http://jsfiddle.net/C2heg/378/
I am litrally banging my head of the table! Hopefully someone can shed some light on this.
Use a - b instead of a > b
$('#numBnt').on('click', function () {
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return parseFloat($(a).find("h2").text().replace(/£/g, '')) - parseFloat($(b).find("h2").text().replace(/£/g, ''));
});
$("#container").html(numericallyOrderedDivs);
});
Demo: http://jsfiddle.net/C2heg/381/
Neither of your fiddles are working, and it has nothing to do with the number of elements.
This works though:
var $divs = $("div.box");
$('#numBnt').on('click', function () {
var numericallyOrderedDivs = $divs.sort(function (a, b) {
var a = parseFloat($(a).find("h2").text().replace(/£/g, ''));
var b = parseFloat($(b).find("h2").text().replace(/£/g, ''));
return a - b;
});
$("#container").html(numericallyOrderedDivs);
});
The sort function on comparing two items should return 0 if they are equal, a positive number if first is greater than second, a negative number otherwise.
Here's the updated fiddle.

wrap more than one nodes with div

How can i wrap exactly half of the div's with another div using jquery or javascript
I have this
<div class="post">1</div>
<div class="post">2</div>
<div class="post">3</div>
<div class="post">4</div>
<div class="post">5</div>
<div class="post">6</div>
I want this
<div class="wrap">
<div class="post">1</div>
<div class="post">2</div>
<div class="post">3</div>
</div>
<div class="wrap">
<div class="post">4</div>
<div class="post">5</div>
<div class="post">6</div>
</div>
Try using this:
var posts = $('.post'),
postCount = posts.length,
postHalf = Math.round(postCount/2),
wrapHTML = '<div class="wrap"></div>';
posts.slice(0, postHalf).wrapAll(wrapHTML); // .slice(0, 3)
posts.slice(postHalf, postCount).wrapAll(wrapHTML); // .slice(3, 6)
This selects all .post, gets the number of elements found then halves that value to get the splitting point. It then uses .slice() to select a specific range of elements and .wrapAll() to wrap each selection in <div class="wrap"></div>.
Here it is working: http://jsfiddle.net/ekzrb/

How do I select a specific double-nested element inside a div without jquery?

I am using a script called swipeview to put multiple instances of a gallery on a page. It generates the structure like this:
<div id="slider-1">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<img src="images/01.jpg" id="one"/>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<img src="images/02.jpg" id="two"/>
</div>
</div>
</div>
<div id="slider-2">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<img src="images/01.jpg" id="one"/>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<img src="images/02.jpg" id="two"/>
</div>
</div>
</div>
The only thing that is unique to each image is the top-level div ID (slider-1, slider-2).
Without using jQuery, how can I get the ID of each separate image within the 'swipeview-active' class?
With jQuery I would select them with something along these lines:
$('#slider-1 > .swipeview-slider > .swipeview-masterpage .swipeview-active > img ').attr('id');
How can I do achieve this in regular js?
First of all: IDs must not start with a digit.
The dot-selector selects elements by class name. Use class=.. instead of id=....
Corrected code, using document.querySelectorAll (demo: http://jsfiddle.net/rGAkm/3/).
var images = document.querySelectorAll('#slider-1 > .swipeview-slider > .swipeview-masterpage .swipeview-active > img[id]');
var len = images.length;
var output = document.getElementById('output');
for (var i=0; i<len; i++) {
var image = images[i];
output.appendChild(image);
}
Replace #slider-1 with [id^="slider-"] if you want to select all images in this structure, which is a child of id="slider-1", id="slider-2", ...
Probably not the most elegant solution, but it works. I replaced the img tags with span tags for demonstration. I also gave the last 2 span tags a different id, and added one extra, to show it working on both root slider divs for any number of spans (images). Hope it helps.
http://jsfiddle.net/vNqhd/3/
html:
<div id="slider-1">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<span id="one">img1</span>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<span id="two">img2</span>
</div>
</div>
</div>
<div id="slider-2">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<span id="three">img3</span>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<span id="four">img4</span>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<span id="five">img5</span>
</div>
</div>
</div>
<button onclick="myfunc('slider-1');">button</button>
<button onclick="myfunc('slider-2');">button</button>
<div id="msg"></div>
js:
function myfunc(divID){
var myVar = document.getElementById(divID);
var imgIDs = [];
var counter = 0;
var str = "";
//walk the DOM from a root div and look for img/span tags
//and store their IDs
while(true){
if(myVar === undefined){ break; }
if(myVar.getElementsByTagName('div').length > 0){
myVar = myVar.getElementsByTagName('div')[0];
continue;
} else if(myVar.getElementsByTagName('span').length > 0){
imgIDs.push(myVar.getElementsByTagName('span')[0].id);
counter++;
myVar = myVar.parentNode.getElementsByTagName('div')[counter];
} else { break; }
}
//display results
for(var i = 0; i < imgIDs.length; i++){
str += imgIDs[i] + "<br/>";
}
document.getElementById('msg').innerHTML = str;
}

Categories