Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery add not-in-dom element in a ordered stack (in-dom elements)

I have an unexpected problem.

HTML

<div id="div1" class="myDiv"></div>
<div id="div2" class="myDiv"></div>
<div id="div3" class="myDiv"></div>
<div id="div5" class="myDiv"></div>
<div id="div6" class="myDiv"></div>

JS

$(function() {
    var $divs = $('.myDiv');
    // create new div not in tree
    var $div = $('<div/>').attr("id","div4").addClass('myDiv');
    // insert #div4 in right position. Only in stack, not in dom tree.
    $divs = $divs.slice(0,3).add($div).add($divs.slice(3));

    console.log($divs);
});

output

[div#div1.myDiv, div#div2.myDiv, div#div3.myDiv, div#div5.myDiv, div#div6.myDiv, div#div4.myDiv]

Warning: I DON'T want to insert it in dom tree (like $div.appendBefore($divs[3])), I just want append it in my stack $divs.

I thought that this stack was an ordered list. So, my goal was to create on fly a #div4 and insert it in $divs stack without insert it in DOM tree. The insert works but it seems that jquery ignore the order given.

I've other solutions for this problem (i.e. append in dom with a display none), ok.. but:

My question is: why? It's a bug for some cache optimization, or it's a documented feature?

I've also tried:

var $newDivs = $();
$divs.each(function(i,e) {
    if(i==3) 
        $newDivs = $newDivs.add($div);
    $newDivs = $newDivs.add(e);
});
console.log($newDivs);

but the output is the same.

EDIT: Just for completeness: this was just a fast hack for a complex code. I know that the purpose is not clean

like image 709
Luca Rainone Avatar asked Nov 16 '25 14:11

Luca Rainone


1 Answers

That's not the purpose of a jQuery object. KEep your data-structures straight; I'm not sure how the concept of a 'stack' came into this at all. Use the regular built in JS arrays (which keep items ordered):

$(function() {
    // make an array of existing divs
    var divs = $('.myDiv').toArray();

    // create new div
    var newDiv = $('<div/>').attr("id","div4").addClass('myDiv').get(0);

    // insert newDiv at index 4 in array
    divs.splice(4, 0, newDiv);

    // Rejoice.
    console.log(divs);
});
like image 100
nbrooks Avatar answered Nov 19 '25 02:11

nbrooks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!