I have 3 divs ( col-md-4
) and I have div blocks inside them. I am trying to get the elements by rows (as if the parent was one col-md-12 rather than their divided col-md-4s) but I couldn't figure out how to achieve it.
To clarify the issue (and simplify it), below I have added data-order
attribute to show it's exact order and how I want them to be ordered.
For preventing confusing, I have updated the question and added data-id
attributes; imagine you don't have data-order
attribute at all; I have only put it just to clarify the order.
<div class="col-md-4 parent">
<div class="child" data-id="3" data-order="1"></div>
<div class="child" data-id="4" data-order="4"></div>
<div class="child" data-id="8" data-order="7"></div>
</div>
<div class="col-md-4 parent">
<div class="child" data-id="1" data-order="2"></div>
<div class="child" data-id="2" data-order="5"></div>
</div>
<div class="col-md-4 parent">
<div class="child" data-id="11" data-order="3"></div>
<div class="child" data-id="7" data-order="6"></div>
</div>
How can I get the elements using a for loop (or foreach) to order those elements?
$('.parent').each(function(index) {
console.log($(this).data('order')); // Using this gives 1, 4, 7, 2, 5, 3, 6
});
// However what I want to achieve is: when looped:
// console.log($(this).data('id')); // "3, 1, 11, 4, 2, 7, 8"
What is the most suitable way to achieve this? How would you handle such case?
Like this:
parent(1)-child(1)
parent(2)-child(1)
parent(3)-child(1)
parent(X)-child(1)
parent(1)-child(2)
parent(2)-child(2)
parent(3)-child(2)
parent(X)-child(2)
parent(1)-child(3)
parent(2)-child(3)
parent(3)-child(3) and so on...
Use a loop that iterates over each parent
until the collection is full:
const collection = []; const totalChildren = $('.child').length; for (let i = 0; collection.length < totalChildren; i++) { $('.parent').each((_, parent) => { if (parent.children[i]) collection.push(parent.children[i]); }); } console.log(collection);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="col-md-4 parent"> <div class="child" data-order="1"></div> <div class="child" data-order="4"></div> <div class="child" data-order="7"></div> </div> <div class="col-md-4 parent"> <div class="child" data-order="2"></div> <div class="child" data-order="5"></div> </div> <div class="col-md-4 parent"> <div class="child" data-order="3"></div> <div class="child" data-order="6"></div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.