简体   繁体   中英

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string. Sample HTML DIV

strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
    <div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
    <div id='multiselectAnchors' type='multi'>
        <div id='options32' >Two</div>
        <div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
    </div>
    <div id='blank4' contenteditable='true' type='blankField'>&nbsp;&nbsp;&nbsp;</div>
    <div id='Div1' type='multi'>
        <div id='options33' >Three</div>
        <div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
    </div>"

here is the code sample

if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {

strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work) 

}

the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest

var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();

var str = el.wrap("<div/>").parent().html()

Generate a DIV dynamically:

$('body').append('<div>');

Access the DIV immediately after generation:

var $divElement = $('body').append('<div>').find('div');

Get the last child:

var $lastChildElement = $divElement.last();

Get the HTML of the last child (more specifically, the innerHTML ):

var $lastChildHTML = $lastChildElement.html();

Do it all together then you turn around:

var $lastChildHTML = $('body').append('<div>').find('div').last().html();

That's what it's all about.

var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

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