jquery从.text()中排除一些子节点
html结构看起来像这样
parent may contain text child 1 may contain text console.log('i always contain something');` child2 may contian text
我试图获取除的内容之外的每个节点的内容。 结果应如下所示:
parent may contain text child 1 may contain text child2 may contian text
我尝试过使用($('#parent').not('div script').text()
,但它不起作用
试试这个
($('#parent').text()).replace($('#parent script').text(),'')
检查这个http://jsfiddle.net/QLBvK/12/
您可以通过克隆节点,删除脚本标记并检索text()
值来实现:
var content = $('#parent').clone(); content.find('script').remove(); console.log(content.text());
DEMO
您应克隆该节点,以便之后确定未更改的DOM树。
这适用于我,看起来非常通用[编辑,以使程序更清晰]
var t = []; $("#parent").each(function(i,e) {if (e.nodeName!="SCRIPT") t.push(e.innerText);}); console.log(t);
您应该显然以其他方式(数组?)收集字符串,而不是使用console.log()
来在代码中使用它们。
一个不错的小jQuery插件: jQuery.ignore()
$.fn.ignore = function(sel){ return this.clone().find(sel||">*").remove().end(); };
使用如下:
$("#parent").ignore() // Will ignore all children elements $("#parent").ignore("script") // Will ignore a specific element $("#parent").ignore("h1, p, .ignore") // Will ignore specific elements
例:
Get this Ignore this Get this paragraph
var ignoreSpanAndFooter = $("#parent").ignore("span, .footer").html();
将导致:
Get this Get this paragraph
来自此答案的片段: https : //stackoverflow.com/a/11348383/383904