Reputation: 32160
<div class="stuff">
<span class="to_hide"> blah </span>
<span id="permanent"> like glue </span>
</div>
I want to grab the $(".stuff").text()
, but I don't the #tmp
's text
This works fine I do $(".to_hide").remove()
But I don't want the removal action to have an effect on the page itself. If I remove it or detach, I need to know where the elements have been (assume many .to_hide
nodes)
How can I use .text()
while ignoring .to_hide
Upvotes: 1
Views: 510
Reputation: 13800
Another approach is to subtract the text you want excluded from the entire chunk of text.
var keep = document.querySelector('.stuff').innerText
var exclude = document.querySelector('.to_hide').innerText
var result = keep.replace(new RegExp(exclude, 'g'), '')
alert(result)
Ultimately, the complexity of the solution will depend on the DOM you expect to be operating on. Also, you don’t gain much by leaning on a DOM library for this.
Upvotes: 0
Reputation: 11114
you need to make a clone then get text from div
var clone =$(".stuff").clone();
clone.find(".to_hide").remove();
var text= clone.text()
console.log(text);
Upvotes: 1
Reputation: 388396
One easy way is to use a clone
var text = $(".stuff").clone().find('.to_hide').remove().end().text();
console.log(text)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="stuff">
<span class="to_hide"> blah </span>
<span id="permanent"> like glue </span>
</div>
You can also do - but if you have complex systems and text nodes which are direct descendants of stuff
this may not work
var text = $(".stuff *").not('.to_hide').text();
console.log(text)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="stuff">
<span class="to_hide"> blah </span>
<span id="permanent"> like glue </span>
</div>
Upvotes: 2