Zoker
Zoker

Reputation: 2059

Clone element to parent

I have this code:

<div class="parent copy">
    <div class="child">
        <a href="#">Text</a>
        <a href="#">Text2</a>
    </div>
</div>

And I want to have this output:

<div class="parent copy">
    <div class="child hidden-xs">
        <a href="#">Text</a>
        <a href="#">Text2</a>
    </div>
    <ul class="child show-xs">
        <li><a href="#">Text</a></li>
        <li><a href="#">Text2</a></li>
    </ul>
</div>

I want to do this for every element on the page with the .copy class.

Basically I know how to do all this stuff on its own, my problem is, to get clone the child and make it more efficient. I tried something like this:

$('.copy .child').clone();
// Problem: How can I append it to the .copy element? .clone().appendTo($(this).parent()); does not work
$('.copy .child:nth-child(1)').addClass('hidden-xs');
$('.copy .child:nth-child(2)').replaceWith($('<ul class="child show-xs>' + this.innerHTML + '</ul>'));
$('.copy .child:nth-child(2) a').wrap('<li></li>');

Is there a way to make this more efficient and easy?

Edit: Here is my own solution based on dreamweiver`s:

$(function () {
    $('.parent .child').addClass('hidden-xs');
    $clone = $('.parent .child').clone();
    $clone.removeClass('hidden-xs').addClass('show-xs').wrapInner( '<ul class="child show-xs"></ul>');
    $clinks = $clone.find('a');
    $clinks.each(function() {
        $(this).wrap('<li></li>');
    });

    $('.parent').append($clone);
});

Upvotes: 1

Views: 1210

Answers (1)

dreamweiver
dreamweiver

Reputation: 6002

When you write some logic make sure you write it in a way others can understand your code easily.

Below is my solution is quite simple, but may require some tuning, which you could probably do it.

JS CODE:

$(function () {
$('.child:eq(0)').addClass('hidden-xs');
$('#clone').on('click', function () {
    var clo = $('.child:eq(0)').clone();
    clo.removeClass('hidden-xs');
    clo.addClass('show-xs');
    var subElements = clo.find('a');
    var $newElement = $('<a/>');

    subElements.each(function () {
        var $liEle = $('<li/>');
        var $newElement = $('<a/>');
        $newElement.html($(this).html());
        $newElement.attr('href', $(this).attr('href'));
        clo.append($liEle.append($newElement));
        $(this).remove();
    });

    $('.parent').append(clo);
    alert($('.parent').html());
});
});

Live Demo @ JSFiddle

Upvotes: 1

Related Questions