Reputation: 71
How do I select the text inside tags excluding the content of other tags. For example:
<div id='id'>text that I want to select<p>text that I don't want</p></div>
In this case, how do I use something like this, to get the plain text?
document.getElementByID('id').innerText
Upvotes: 1
Views: 199
Reputation: 33439
console.clear()
function noChildTextContent(el) {
var clone = el.cloneNode(true);
var childNodes = clone.childNodes;
var ret = "";
for (let childNode in childNodes) {
if (childNodes.hasOwnProperty(childNode)) {
if (childNodes[childNode].nodeType == 3) {
ret += ` ${childNodes[childNode].textContent}`
}
}
}
return ret.trim();
}
console.log(noChildTextContent(document.getElementById('id')))
<div id='id'>text that I want to select<p>text that I don't want</p>Want it again</div>
Upvotes: -1
Reputation: 2035
somthing like that can do
var t =
(document.getElementById("id") ).childNodes
for (let index = 0; index < t.length; index++) {
const element = t[index];
if( element.tagName === undefined ){ document.getElementById("out").append(element.cloneNode()) ;}
}
<div id='id'>text that I want to select<p>text that I don't want</p></div>
<div id="out" style="color:blue"></div>
Upvotes: -1
Reputation: 80
You can also use XPATH in order to select your element's own text
var result = document.evaluate( "//div[@id='id']/text()", document, null, XPathResult.STRING_TYPE, null );
alert(result.stringValue)
<div id='id'>
text that I want to select
<p>text that I don't want</p>
</div>
Upvotes: 0
Reputation: 1073978
To do that, you loop through the text nodes in the element, ignoring the non-text nodes (which includes child elements):
var element = document.getElementById("id");
var text = "";
for (var child = element.firstChild;
child;
child = child.nextSibling) {
if (child.nodeType === Node.TEXT_NODE) {
text += child.nodeValue;
}
}
console.log(text);
<div id='id'>text that I want to select<p>text that I don't want</p></div>
Upvotes: 4