简体   繁体   中英

JQuery `wrap` not working with append

I have a function that is suppose to return several HTML elements wrapped in span tags. The elements are returned, by they are not wrapped in the tag.

This is my code:

function summerizeEdit(edit) {
    var editHtmlBody = '<div>' + edit.content + '</div>';
    var $editElements = $(editHtmlBody).find(EDIT_SELECTORS_TO_SUMMERIZE.join(', '));
    var $editSummery = $('<div />').append($editElements.wrap('<span class="test"/>'));
    return $editSummery.html();
}

The jQuery .wrap method wraps the selected elements, and then returns the selected elements. Therefore, you'll need to select the wrapper if you want the wrapper to be appended rather than the selected elements.

$('<div>').append(el.wrap('<span>').parent());

 $("#target").append($("<div>").wrap("<div class='test'></div>").text("Hello World!").parent()); 
 .test { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="target"></div> 

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