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

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Survey Acct
  • 133
  • 1
  • 5

4 Answers4

7

You can achieve that by cloning your node, removing the script tags and retrieving the text() value:

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

DEMO

You should clone the node in order to asure an unchanged DOM tree afterwards.

Alp
  • 29,274
  • 27
  • 120
  • 198
6

Try this:

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

Check out this Fiddle.

Alexandre Aimbiré
  • 1,494
  • 2
  • 14
  • 26
Muthukumar M
  • 1,138
  • 10
  • 19
  • (1) Your fiddle does not include jQuery. (2) You've spelt `write` wrong so your fiddle throws a SyntaxError even if you include jQuery. (3) If you [fix both of those](http://jsfiddle.net/QLBvK/4/), the contents of the `script` element is written to the page. – James Allardice Jun 30 '12 at 01:00
  • Thanks! it works and is a quick fix, exactly what I'm looking for. – Survey Acct Jun 30 '12 at 01:43
4

This works for me and seems very generic [EDITED to make the procedure clearer]

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

Instead of console.log() you should obviously collect the strings in some other way (array?) to use them in your code.

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

Cranio
  • 9,647
  • 4
  • 35
  • 55
4

A nice small jQuery plugin: jQuery.ignore()

$.fn.ignore = function(sel){
  return this.clone().find(sel||">*").remove().end();
};

Use like:

$("#parent").ignore()                  // Will ignore all children elements
$("#parent").ignore("script")          // Will ignore a specific element
$("#parent").ignore("h1, p, .ignore")  // Will ignore specific elements

Example:

<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();

will result in:

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

Snippet from this Answer: https://stackoverflow.com/a/11348383/383904

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313