1

I have the following string and code:

str = `<p class="">Lores Ipsimulm</p><p class="">1 x 100ml  - 19% </p><p class="">1 x 100ml No.6 Mike</p><p class="">1 x 100ml No.3</p><`
var p = document.createElement("p");
p.textContent = str;
var converted = p.innerHTML;

document.getElementById("final").value = converted;

How do I trim all HTML elements including classes, their name, and other attributes?

Vitalik Jimbei
  • 141
  • 1
  • 9
  • 1
    Can you mention how exactly you want the result? for example, what do you mean by trimming HTML elements? If you want the HTML elements in the string to get applied to the element with id `final`, you can use: `document.getElementById('final').innerHTML = str;`. If it doesn't answer your question, mention additional details – Geeky Quentin May 17 '22 at 10:59
  • 1
    Does this answer your question? [Remove specific HTML tag with its content from javascript string](https://stackoverflow.com/questions/45262311/remove-specific-html-tag-with-its-content-from-javascript-string) – K Scandrett May 17 '22 at 11:10
  • Why take the `innerHTML`? Take the [innerText](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText). – Peter Krebs May 17 '22 at 12:13
  • the result i am looking for is: Lores Ipsimulm 1 x 100ml - 19% 1 x 100ml No.6 Mike1 x 100ml No.3 – Vitalik Jimbei May 17 '22 at 14:12
  • `innerText` can do that. See answer below. – Peter Krebs May 17 '22 at 14:39

1 Answers1

0

set with .innerHTML, get with .innerText

You can use innerText to get the text-only representation of an element's innerHTML. So you set the .innerHTML value and get the text using .innerText.
innerText will use the raw text with the exact spaces existing in the HTML. If you want to format the text for every p tag, you must loop through them.
See example snippet below for .innerText usage.

var str = `<p class="">Lores Ipsimulm</p><p class="">1 x 100ml - 19% </p><p class="">1 x 100ml No.6 Mike</p><p class="">1 x 100ml No.3</p>`;
var p = document.createElement("p");
p.innerHTML = str;
var converted = p.innerText;

console.log(converted);

You set the HTML value with innerHTML, but you get the text using innerText as shown in the snippet.

Your example HTML has an open < at the end. Make sure to use valid HTML.

Peter Krebs
  • 3,831
  • 2
  • 15
  • 29