#HateSO.
So for any given element in a HTML document I need to select the text of that node. For example, consider the following:<span class="1234124655G">
Welcome to
<strong class="1234567">
LOREM IPSUM
</strong>
</span>
Desired ouput:Welcome to
I've attempted the following:.textContext returns all text of all children.nodeValue can return null values..text Returns undefined..innerHTML returns all children elements and their text.
My only thought now is to clone the element and it's children, fetch the children and then remove the children from the clone. But this just seems stupid. Surely there's a way to select the text of a single element?
It's easy when the element has no children, but when it does, like the example above, then I've not found a way to do it. Please advise.
Summed up, I'm trying to do the following (Just a arbitrary object.):object = {};object.innerText = element.textContent;
Also can't use any frameworks.
Specific framework? Vanilla JS? AJS? React?
A sample of code would help us solve the problem.
.textContent does exactly what you ask, however, as I understand you want to concatenate only the text of direct child text nodes and do not include text of child tags.
Still can't understand the use case, that's why textContent works as it is. Nevertheless, here is an example how you can achieve what you want:
function getElementText(element) {
let res = '';
[].forEach.call(element.childNodes, node => res += node.nodeType === Node.TEXT_NODE ? node.textContent : '');
return res;
}
Anyway in your example, you won't get Welcome to, you will get Welcome to (With spaces around, Markdown doesn't displays them to you here). If you want to remove extra spaces, you could apply also trim().
Did you try
var span = document.getElementsByClassName("yourSpan");
console.log(span.item(0).firstChild.textContent);
That I can explain easily.
" Welcome to "is a child of this span. You see this by watching your HTML code.<span> everything inside angle brackets > and < is a child of the surrounding HTML element.</span>When you access the span via
const mySpan = document.getElementsByClassName('1234124655G')You get an array with at least the span from above inside. In your browser, you can run
console.dir(mySpan)to see the structure of this array. You'll quickly spot that the span has some children of its own.console.dir(mySpan[0].childNodes)returns a list with three elements inside - a text element, a strong element and again a text element. The first text element holds your desired text.console.dir(mySpan[0].childNodes[0].data) // " Welcome to "console.dir(mySpan[0].childNodes[0].nodeValue) // " Welcome to "console.dir(mySpan[0].childNodes[0].textContent) // " Welcome to "console.dir(mySpan[0].childNodes[0].wholeText) // " Welcome to "