[英]How to select only text in a div containg other div in jQuery?
我有这个代码:
<div class="bodytext1typeenc">Ce qu’il faut retenir
<div class="al">Budget «solidarités».</div>
</div>
我只想获取“ Ce qu'il faut retenir”。 我已经试过了:
$('.bodytext1typeenc').text() // --> doesn't work.
$('.bodytext1typeenc').remove('.al') // --> doesn't work.
有什么帮助吗? 谢谢 !
您可以克隆,删除子级并获取文本。 见下文,
var $clone = $('.bodytext1typeenc').clone();
$clone.children().remove()
$clone.text(); //should return the div's text
注意:如果您不想保留原始内容,则无需克隆。
演示: http : //jsfiddle.net/PX2yA/
嘿,尝试一下,您要做的就是克隆您的元素,然后删除您的子元素
$(".bodytext1typeenc")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
如果您打算在这里大量使用它,则可以创建一个简单的扩展,例如
jQuery.fn.noChild= function() {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
然后跑
$(".bodytext1typeenc").noChild();
您可以使用contents()并过滤出noteType TEXT_NODE(3)
var val = $('.bodytext1typeenc').contents().filter(function() {
return this.nodeType == 3;
}).text();
val = $.trim(val);
alert('"' + val + '"'); // "Ce qu’il faut retenir"
演示: http : //jsbin.com/AsilIpo/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.