user9735220
user9735220

Reputation:

JS - how to get a string of outerHTML textContent?

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

Upvotes: 0

Views: 4324

Answers (2)

Daut
Daut

Reputation: 2625

.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

Upvotes: 1

R3tep
R3tep

Reputation: 12854

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>

Upvotes: 1

Related Questions