Sometimes, we want to get the text node of an element with JavaScript.
In this article, we’ll look at how to get the text node of an element with JavaScript.
How to get the text node of an element with JavaScript?
To get the text node of an element with JavaScript, we call array find
to find the text node in a node.
For instance, we write
const extract = (node) => {
const text = [...node.childNodes].find(
(child) => child.nodeType === Node.TEXT_NODE
);
return text?.textContent?.trim();
};
to create the extract
function that takes the node
and get the child nodes with node.childNodes
.
Then we spread the child nodes into an array.
And we call find
with a callback that gets the nodeType
with type Node.TEXT_NODE
.
Finally, we get the textContent
of the text
node.
Conclusion
To get the text node of an element with JavaScript, we call array find
to find the text node in a node.