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

时间:2013-08-29 13:57:30

标签: javascript jquery html jquery-ui

如何删除动态生成的div的lastchild并将html重新生成为字符串。 示例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>"

这是代码示例

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) 

}

需要在运行时删除div的lastchild并转换回字符串,就像之前一样。我可以做字符串操作,但可能不是正确的方法,请建议

3 个答案:

答案 0 :(得分:2)

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()

答案 1 :(得分:1)

动态生成DIV:

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

生成后立即访问DIV:

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

得到最后一个孩子:

var $lastChildElement = $divElement.last();

获取最后一个孩子的HTML(更具体地说,innerHTML):

var $lastChildHTML = $lastChildElement.html();

一起完成然后你转身:

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

这就是它的全部内容。

答案 2 :(得分:1)

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();