在div中获取文本

可能重复:
jquery – 获取没有子文本的元素的文本

我有一个文本里面的div和文本之后的跨度如下:

text other text

而且我想只在div中获取文本而不是跨度

谢谢

您可以使用.clone() ,如下所示:

 b = $('div').clone(); b.children('span').remove(); alert( b.text() ); // alerts "text" 

使用.clone()我们可以复制div,删除span,然后获取文本,所有这些都不会影响页面上显示的原始DOM元素。

试试这个

  var myText = $('#dd').clone() .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text(); //get the text of element 
 var theText = ""; $('div').contents().each(function() { if(this.nodeType === 3) theText += $(this).text(); });