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
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
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.
Try this:
($('#parent').text()).replace($('#parent script').text(),'');
Check out this Fiddle.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With