b0y b0y - 5 months ago 12
HTML Question

get sequence of div from html

I have 9 HTML divs as:

<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>


<div id="9">9</div>


Now sequence in HTML is : (id) 1 2 3 4 5 6 7 8 9

These divs can be rearranged to get any order in the DOM.

Say after swapping the DOM is like this:

<div id="8">8</div>
<div id="2">2</div>
<div id="5">5</div>


<div id="1">1</div>


(after swapping/reordering) Now sequence in HTML is : (id) 8 2 5 3 4 7 9 6 1

I want to get the order(8 2 5 3 4 7 9 6 1) of div in a span.

<div id="show">Now the sequence is <span id="seq"> </span></div>

Answer

Use a common class to get all the div that you need. Then use each to get it's text(or id) and form a string and append it to the dom

HTML

<div id="8" class="sqDiv">8</div>
<div id="2" class="sqDiv">2</div>
<div id="5" class="sqDiv">5</div>
<div id="1" class="sqDiv">1</div>
<span id="sqDom"></span>

JS

var _sq="";
var getDivs = $(".sqDiv");
getDivs.each(function(item,index){

 _sq+=$(this).text().trim()+' ';
})
$("#sqDom").text(_sq);

JSFIDDLE