简体   繁体   中英

Jquery wrap function inside div

How do I wrap a function inside a div that doesn't exist?

So far, I've tried .append before and after, but that closes the tag. Also tried .html, and wrap right after the function, no luck.

$("#testing .input").each(function() {
    var s = $(this).find("li .value").text();
    // start wrap
    $("span.rune > span", this).each(function() {
        var e = $(this).text();
        $("#test-output").append('<span class="' +e+ ' Rune"></span>');
    });
    // stop wrap
    $("#test-output").append('<span>' +txtToNumber[s]+ '</span>');
});

Starting HTML :

<div id="test-output"></div>

Ending HTML :

<div id="test-output">
    <div class="three">
        <span class="Z Rune"></span>
        <span class="Y Rune"></span>
        <span class="X Rune"></span>
    </div>
</div>

Thanks!

You can create elements in jQuery without appending them. Then they basically "don't exist yet", at least not in the DOM (they are disconnected). What you can also do is creating the .three element, append it to the DOM, and then append the .Rune elements to it:

// create .three element and append it to the DOM
var $three = $("<div>").addClass("three").appendTo("#test-output");

// map these elements to .Rune elements
$("span.rune > span", this).map(function() {
    var e = $(this).text();

    return $("<span>")
             .addClass(e)
             .addClass("Rune")
             .get(0);
}).appendTo($three);  // and append them to .three

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM