Reputation: 405
I'm looking to try and do a querySelector for text that avoids picking up a div within the content. Any thoughts gratefully appreciated.
JS
domdoc.querySelector('li.list_item').textContent
HTML:
<li class="list_item">
Hello
<a>
world,
<div id="tooltip">
Please ignore this
</div>
</a>
how are you
</li>
Returns:
Hello world, Please ignore this how are you
Would like to see:
Hello world, how are you
Upvotes: 3
Views: 1817
Reputation: 4729
Simply replace
the tooltip text and trim whitespaces.
const text = document.querySelector(`li.list_item`).textContent
const tooltip = document.querySelector(`#tooltip`).textContent
const message = text.replace(tooltip, ``).replace(/\s+/g, ` `).trim()
console.log(message)
<li class="list_item">
Hello
<a>
world,
<div id="tooltip">
Please ignore this
</div>
</a>
how are you
</li>
Upvotes: 2
Reputation: 943979
querySelector
will select an element, not an element and its descendants.
textContent
including descendants of the list item is a feature of textContent
, not of querySelector
.
You can clone the list item, remove the div from it, then get the textContent of that.
var li = document.querySelector('li.list_item');
var duplicate = li.cloneNode(true);
duplicate.querySelector("div").remove();
console.log(duplicate.textContent);
<ul>
<li class="list_item">
Hello
<a>
world,
<div id="tooltip">
Please ignore this
</div>
</a> how are you
</li>
</ul>
Upvotes: 3