0

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>&nbsp;&nbsp;&nbsp;Hello World <img alt="imageText" src="image/source"></img></div>

I would want to get the string " Hello World imageText"

rtpax
  • 1,687
  • 1
  • 18
  • 32
  • 3
    `innerText` will get you close, but not the image text. – David Hedlund Oct 18 '16 at 06:16
  • May be what you want is this feature https://www.fullstory.com – Cristofor Oct 18 '16 at 06:16
  • Possible duplicate of [How to unescape html in javascript?](http://stackoverflow.com/questions/1090056/how-to-unescape-html-in-javascript) – Niko Oct 18 '16 at 06:19
  • That question is more about security, and it doesn't seem to deal with the image in the innerHTML – rtpax Oct 18 '16 at 06:30
  • Possible duplicate of [Unescape HTML entities in Javascript?](http://stackoverflow.com/questions/1912501/unescape-html-entities-in-javascript) – rbntd Oct 18 '16 at 06:35

1 Answers1

2

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>&nbsp;&nbsp;&nbsp;Hello World <img alt="imageText" src="image/source"></img></div>
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137