13

The html structure looks like this

<div id="parent">
    parent may contain text
    <div id="child1">
       child 1 may contain text
       <script>console.log('i always contain something');</script>`
    </div>

    <div id="child2">
       child2 may contian text
    </div>    
</div> 

I am trying to get contents of every node except the contents of <script>. The result should look like this:

    parent may contain text
    child 1 may contain text 
    child2 may contian text

I've tried using ($('#parent').not('div script').text() ,but it does not work

4

4 回答 4

7

您可以通过克隆节点、删除脚本标签并检索text()值来实现:

var content = $('#parent').clone();
content.find('script').remove();
console.log(content.text());

演示

您应该克隆该节点以确保之后保持不变的 DOM 树。

于 2012-06-30T01:22:13.263 回答
6

尝试这个:

($('#parent').text()).replace($('#parent script').text(),'');

看看这个小提琴

于 2012-06-30T00:57:45.440 回答
4

一个不错的小型 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

例子:

<div id="parent">
   Get this
   <span>Ignore this</span>
   <p>Get this paragraph</p>
   <div class="footer">Ignore this</div>
</div>

var ignoreSpanAndFooter = $("#parent").ignore("span, .footer").html();

将导致:

Get this
<p>Get this paragraph</p>

此答案的片段:https ://stackoverflow.com/a/11348383/383904

于 2014-12-23T17:13:54.157 回答
4

这对我有用,看起来很通用[编辑以使程序更清晰]

var t = [];
$("#parent").each(function(i,e) 
    {if (e.nodeName!="SCRIPT") t.push(e.innerText);}​);​​​​​​​​​​​​​​
console.log(t);

而不是console.log()您显然应该以其他方式(数组?)收集字符串以在您的代码中使用它们。

http://jsfiddle.net/8eu4W/3/

于 2012-06-30T01:09:19.953 回答