Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery exclude some child nodes from .text()

Tags:

jquery

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

like image 586
Survey Acct Avatar asked Jun 30 '12 00:06

Survey Acct


4 Answers

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

like image 112
Roko C. Buljan Avatar answered Sep 26 '22 05:09

Roko C. Buljan


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.

like image 20
Alp Avatar answered Nov 10 '22 08:11

Alp


Try this:

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

Check out this Fiddle.

like image 6
MMK Avatar answered Nov 10 '22 10:11

MMK


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/

like image 4
Cranio Avatar answered Nov 10 '22 09:11

Cranio