通过jquery从主DIV获取带有html标签的文本?

时间:2013-06-18 13:06:21

标签: jquery text

如何使用html标签获取文本,但仅限于主DIV?没有形成其他DIVS。

以下是示例,但存在一些问题,因为文本没有html标记< br />

jsFiddle DEMO

HTML

<div id='parent'>
    this text is <br />for parent

   <div id='child-parent'> 
     this text if for child-parent  
       <div id='child'>
        and this text is for child.   
       </div>   
   </div>
</div>

的jQuery

alert($('#parent').clone().children().remove().end().html());

2 个答案:

答案 0 :(得分:1)

我更新了你的小提琴并使用了不同的策略来移除最后一个元素

http://jsfiddle.net/F6AeM/1/

var parent = $('#parent').clone();
$(parent).find('#child-parent').remove();
alert($(parent).html());

不确定为什么会这样,但是你的不行,但是你走了。

答案 1 :(得分:1)

假设child-parentchild将始终拥有id

var clone = $('#parent').clone();
clone.children().filter(function () {
    return $(this).is('[id]');
}).remove();

console.log(clone.html());

演示---> http://jsfiddle.net/F6AeM/5/