Reputation: 1777
You can get what the code has stored in an html element with innerHTML
. Is there any way to show what a user would get if they copied and pasted the content in the rendered version.
For example, if you had the div
<div> Hello World <img alt="imageText" src="image/source"></img></div>
I would want to get the string " Hello World imageText"
Upvotes: 0
Views: 89
Reputation: 40566
You can use a recursive function to get the text content of all child nodes:
function getText(node) {
switch (node.nodeType){
case Node.ELEMENT_NODE:
if (node.tagName === 'IMG') {
return node.getAttribute('alt');
} else {
var children = Array.prototype.slice.call(node.childNodes);
return children.map(getText).join('');
}
case Node.TEXT_NODE:
return node.textContent;
}
}
var div = document.querySelector('div');
console.log(getText(div));
<div> Hello World <img alt="imageText" src="image/source"></img></div>
Upvotes: 2