rtpax
rtpax

Reputation: 1777

Get what html element shows user

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"

Upvotes: 0

Views: 89

Answers (1)

Cristian Lupascu
Cristian Lupascu

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

Upvotes: 2

Related Questions