I am trying to extract text from an html string but, it is not working as expected.
The html string I have is,
<div data-content-type="html" data-appearance="default" data-element="main"><p>The Angelina Tank Dress is simple yet sophisticated. This dress can be thrown over a swimsuit for last minute lunch plans or belted for dinner on the patio. The high-low hemline gives it the perfect amount of swing. </p><p>Features:</p><ul><li>Scoopneck</li><li>Sleeveless</li><li>Hits below the knee</li><li>Longer back hemline</li><li>Machine wash, tumble dry low</li></ul></div>
There is a description text and text inside the ul li elements. How could I extract all of that text separately. For example, extract the description text separately and the text inside li elements separately.
I tried
const productDescription = productDetails.description.replace(/<div>|<\/div>|<ul>|<li>/g, "").trim().split("Features:");
I would like the text to be
The Angelina Tank Dress is simple yet sophisticated. This dress can be thrown over a swimsuit for last minute lunch plans or belted for dinner on the patio. The high-low hemline gives it the perfect amount of swing.
Scoopneck Sleeveless Hits below the knee Longer back hemline Machine wash, tumble dry low
querySelectorAll to find all the p and li elements.map).type and text properties.const html = document.querySelector('div').textContent;
const div = document.createElement('div');
div.innerHTML = html;
const els = div.querySelectorAll('p, li');
const arr = Array.from(els).map(el => {
const type = el.nodeName === 'P' ? 'para' : 'item';
return { type, text: el.textContent }
});
console.log(arr);
<div data-content-type="html" data-appearance="default" data-element="main"><p>The Angelina Tank Dress is simple yet sophisticated. This dress can be thrown over a swimsuit for last minute lunch plans or belted for dinner on the patio. The high-low hemline gives it the perfect amount of swing. </p><p>Features:</p><ul><li>Scoopneck</li><li>Sleeveless</li><li>Hits below the knee</li><li>Longer back hemline</li><li>Machine wash, tumble dry low</li></ul></div>
<script>
function stripHtml(html) {
var textarea = document.createElement("textarea");
textarea.innerHTML = html;
var temporalDivElement = document.createElement("p");
temporalDivElement.innerHTML = textarea.value;
return temporalDivElement.textContent || temporalDivElement.innerText || "";
}
var htmlString = `<div data-content-type="html" data-appearance="default " data-element="main"><p>The Angelina Tank Dress is simple yet sophisticated. This dress can be thrown over a swimsuit for last minute lunch plans or belted for dinner on the patio. The high-low hemline gives it the perfect amount of swing. </p><p>Features:</p><ul><li>Scoopneck</li><li>Sleeveless</li><li>Hits below the knee</li><li>Longer back hemline</li><li>Machine wash, tumble dry low</li></ul></div>`;
console.log(stripHtml(htmlString));
</script>