简体   繁体   English

如何删除动态生成的DIV的lastchild元素并将html作为字符串返回

[英]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. 如何删除动态生成的div的lastchild并将html重新生成为字符串。 Sample HTML DIV 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. 需要在运行时删除div的lastchild并转换回字符串,就像之前一样。 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: 动态生成DIV:

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

Access the DIV immediately after generation: 生成后立即访问DIV:

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 ): 获取最后一个孩子的HTML(更具体地说,是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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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