0

question in JavaScript - I defined an element using tagName, and I want to get the string of it's full define (like "

let elem = elementsArr[i].outerHTML.textContent;

it returns me undefined. I'd like some help :)

Just want to know why my code doesn't work

  • Possible duplicate of [How to get the HTML for a DOM element in javascript](https://stackoverflow.com/questions/1763479/how-to-get-the-html-for-a-dom-element-in-javascript) – nano Feb 22 '19 at 14:16
  • i'm flagging this as a duplicate of https://stackoverflow.com/questions/1763479/how-to-get-the-html-for-a-dom-element-in-javascript – nano Feb 22 '19 at 14:17
  • 1
    that's an other solution to solve my problem, but i want to know why what i 've tried to do doesn't work.. –  Feb 22 '19 at 14:20
  • @Aragog what's the html? –  Feb 22 '19 at 14:23

2 Answers2

1

Just want to know why my code doesn't work

Because .outerHTML haven't method .textContent, so it returns undefined.

If you want to get the content of the element you can use .innerHTML.

Or if you want only the text, you can use .textContent on the element.

See example :

d = document.getElementById("d");
console.log(d.outerHTML);
console.log(d.innerHTML);
console.log(d.textContent); 
<div id="d"><p>Content</p><p>Further Elaborated</p></div>
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • 1
    Exactly - [`Element.outerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) returns a String (basically). [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent) is a method on Node objects. – lemieuxster Feb 22 '19 at 14:28
1

.outerHTML returns a string, and String has no method textContent as it is all text content;

You can clear out the HTML with a RegEx or with a function - see below:

This returns all the text with none of the tags :)

function strip(html) {
  var doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
}

demo = document.getElementById("demo");

console.log(strip(demo.outerHTML));

console.log(demo.outerHTML.replace(/<(?:.|\n)*?>/gm, '')); // even simpler
<div id="demo">
  <p>Some </p>
  <p>text <span>here</span></p>
</div>

reference: Strip HTML from Text JavaScript

EDIT: You can also just use element.textContent and it will return exactly what you want

Daut
  • 2,537
  • 1
  • 19
  • 32
  • 1
    I think you can use directly `.textContent` instead `.outerHTML` with regex. There is a diffrence ? – R3tep Feb 22 '19 at 14:39