Recursively change the type of an element with jQuery, why does it partially work?

Source node:

 <div class="tree">
    <div class="item"><!-- replaced OK -->
        <a href class="toggle">+</a>
        <a href class="name">Name</a>
        <div class="collapse">
            <div class="item"><!-- this wouldn't be replaced ?! --></div>
        </div>
    </div>
    <div class="item"></div><!-- replaced OK -->
</div>

      

I need to clone these nodes and recursively replace each <div class="item">

with <li class="item">

and <div class="collapse">

with <ul class="collapse">

.

For elements, this will only work for the first level:

var $clone = $('.tree').clone(false);

$clone
    .find('.item')
    .replaceWith(function () {
        return $('<li>'+$(this).html()+'</li>');
    });

      

Is there something wrong with my code?

+3


source to share


2 answers


Your function replacement will replace the html inside the first .item

with new html elements. Thus, the other .item

in the returned array .find()

no longer exists. You can put this in a while loop, so everything is .item

replaced with li

s:

var $items=$clone.find(".item");
while($items.length>0){
    $items.replaceWith(function () {
        return $('<li>'+$(this).html()+'</li>');
    });
    $items=$clone.find(".item");
}

      



JSFiddle: http://jsfiddle.net/j14f0bx9/

+1


source


You can search for .tree

and replace each one .item

this way (I removed $clone

):

$('.tree').find($('.item')).each(function( index ) {
    $(this).replaceWith($("<li>").append($(this).contents()));
});

      



JSFIDDLE: http://jsfiddle.net/ghorg12110/k3g5783b/

0


source







All Articles