Created
May 16, 2021 11:15
-
-
Save Debdut/fedf5e799c0977f42143d96776caae61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const NONTEXT_TAGS = [ 'SCRIPT', 'STYLE', 'IMAGE', 'VIDEO', 'AUDIO' ] | |
function isTextNode (node) { | |
return NONTEXT_TAGS.indexOf(node.tagName) === -1 | |
} | |
// Inner Text Less Code, But Slower | |
function innerText (node) { | |
if (node.constructor.name === 'Text') { | |
return node.textContent | |
} | |
return Array | |
.from(node.childNodes) | |
.filter(isTextNode) | |
.map(innerText) | |
.reduce((a, c) => a+c, '') | |
} | |
// Inner Text Faster, Recommended | |
function innerText (node) { | |
if (node.constructor.name === 'Text') { | |
return node.textContent | |
} | |
let text = '' | |
const childNodes = node.childNodes | |
for (let i = 0; i < childNodes.length; i++) { | |
const childNode = childNodes[i] | |
if (isTextNode(childNode)) { | |
text += innerText(childNode) | |
} | |
} | |
return text | |
} | |
// What's the problem with this? | |
// This seems the best and fastest | |
function innerText (node) { | |
return node.textContent | |
} | |
// And lastly don't copy paste answers | |
// from Stack or anywhere else | |
// see the code, understand and then write | |
// your own code, otherwise, you get these | |
// callbacks which are 2010ish javascript | |
// Copy Paste works for consultancies lol | |
// You shouldn't do that when you're | |
// writing for your own | |
// You're cheating yourself | |
// Problems with Your Code | |
// It doesn't return the Whole Text | |
// It can only print | |
// while is useless! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment