jQuery Concatenate multiple DOM node references into one list
Lets say for example I have the following HTML:
<div class="level0">
<div>level 0 #1</div>
<div class="contents">
<div class="level1">
<div>level 1 #1</div>
<div class="contents">
<div class="level2"><div>level 2 #1</div></div>
</div>
</div>
</div>
</div>
<div class="level0">
<div>level 0 #2</div>
<div class="contents">
<div class="level1"><div>level 1 #2</div></div>
<div class="level1"><div>level 1 #3</div></div>
<div class="level1">
<div>level 1 #4</div>
<div class="contents">
<div class="level2"><div>level 2 #2</div></div>
<div class="level2"><div>level 2 #3</div></div>
</div>
</div>
</div>
</div>
<div class="level0"><div>level 0 #3</div></div>
I want to get all of the references to nodes with class "level0",
"level1", or "level2". Then I want to iterate over them starting with the
"level2" references, then going to "level1", then "level0".
For instance, the following code would work for what I am trying to do:
$(".level2").each(function(){
console.log($(this).children().first().text());
});
$(".level1").each(function(){
console.log($(this).children().first().text());
});
$(".level0").each(function(){
console.log($(this).children().first().text());
});
That would make the console output be the following:
level 2 #1
level 2 #2
level 2 #3
level 1 #1
level 1 #2
level 1 #3
level 1 #4
level 0 #1
level 0 #2
level 0 #3
As you can see, they are in order based on class, THEN by order in the
HTML from top to bottom. This is what I want
However, I want to store this list of elements in this order so I can just
use one loop for all of the elements.
The following code is similar to what I want but displays iterates through
the rows in the wrong order.
var $rows = $(".level2, .level1, .level0");
$rows.each(function(){
console.log($(this).children().first().text());
});
This iterates through the rows using in-order traversal. Is there any way
to append these rows into a single variable that I can iterate over in the
order I wanted way above?
No comments:
Post a Comment