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

4
  • Possible duplicate of How to get the HTML for a DOM element in javascript Commented Feb 22, 2019 at 14:16
  • i'm flagging this as a duplicate of stackoverflow.com/questions/1763479/… Commented Feb 22, 2019 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.. Commented Feb 22, 2019 at 14:20
  • @Aragog what's the html? Commented Feb 22, 2019 at 14:23

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly - Element.outerHTML returns a String (basically). textContent is a method on Node objects.
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

1 Comment

I think you can use directly .textContent instead .outerHTML with regex. There is a diffrence ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.