Smila
Smila

Reputation: 1140

How to get clone element and add div tag before appending

I get the clone elements from iframe html using queryselectorall and also append to another element. I want to add surounding div tag for each query selector element before appending.

Now i have output like this

    <div class="optedit_summary" id="opteditsum">
    <span id="pc1430568488933" class="optbold">nde</span>
    <span id="pc1430568582173" class="optdel">fas</span>
    <span id="pc1430914284123" class="optdel">non</span>
    </div>

Need as like below

    <div class="optedit_summary" id="opteditsum">
    <div><span id="pc1430568488933" class="optbold">nde</span></div>
    <div><span id="pc1430568582173" class="optdel">fas</span></div>
    <div><span id="pc1430914284123" class="optdel">non</span></div>
    </div>

This is my code for cloning and append element

    var elements = document.getElementById('main_iframe').contentDocument.querySelectorAll(".optdel, .optbold");
    var editsummary = document.getElementById("opteditsum");

    for (var i = 0, im = elements.length; im > i; i++) {
        editsummary.appendChild(elements[i].cloneNode(true));
    }

Upvotes: 1

Views: 2067

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Since your solution does not use jQuery, you can create a div element then append the clone to that element like

var elements = document.getElementById('main_iframe').contentDocument.querySelectorAll(".optdel, .optbold");
var editsummary = document.getElementById("opteditsum");

var div;
for (var i = 0, im = elements.length; im > i; i++) {
    div = document.createElement('div');
    div.appendChild(elements[i].cloneNode(true))
    editsummary.appendChild(div);
}

Using jQuery the entire code can be as simple as

var $els = $('#main_iframe').contents().find('.optdel, .optbold');
$els.clone().wrap('<div />').parent().appendTo('#opteditsum');

Upvotes: 1

Related Questions