1

I'm using xmldom in a React script, basically im getting a post with a lot of 'dirty' html from a backend and i'm trying to clean and rebuild it i'm using something like:

const { DOMParser } = require('xmldom');
let parser = new DOMParser();
let doc = parser.parseFromString(post.content, 'text/html');
let newContent = [];
for (let i = 0; i < doc.childNodes.length; i++) {
if (doc.childNodes[i].tagName === 'p') {
  newContent.push({
    type: 'p',
    content: doc.childNodes[i].textContent,
    class: doc.childNodes[i].getAttribute('class'),
  });
}

(im also doing it for other tags, like "figure" "iframe" and so on) then in my return function, i map newContent and print it out

it is working correctly, but instead that the textContent from my p block i would preserve the html tags (, and so on), tried a lot of combination but they all return undefined for example:

content: doc.childNodes[i].outerHTML
content: doc.childNodes[i].innerHTML
content: doc.childNodes[i].getElementsByTagName('p').outerHTML
content: doc.childNodes[i].getElementsByTagName('p').innerHTML

none of them and other bunch of combination seems to return the HTML content of the p tag i am in am i doing something wrong? how can i fix it?

popeating
  • 386
  • 1
  • 2
  • 16
  • [This might help](https://stackoverflow.com/questions/37337289/react-js-set-innerhtml-vs-dangerouslysetinnerhtml) – Zach Jensz Mar 20 '22 at 20:52
  • Thank you @ZachJensz but this does not look as my case, my main problem is getting the HTML content of a p node using xmldom (i can only get the content as text) and it seems like its not possible – popeating Mar 20 '22 at 21:00
  • Can you make it a snippet with some example data so I can poke around? – Zach Jensz Mar 20 '22 at 21:04
  • Why you use xmldom to parse html? Why not sometnihg like https://www.npmjs.com/package/react-html-parser or https://www.npmjs.com/package/html-react-parser ? – Nemanja Mar 21 '22 at 14:12
  • i switched yesterday to that package, but still it took me a lot to achieve the desired result – popeating Mar 21 '22 at 16:08

1 Answers1

0

I am new to development and recently had a task to parse the product.description from backend to the product page. I did this way, not sure if it is correct, but maybe it will help you. I did a class component in react and render it in my page like next:

export default class ProductDescription extends Component {
    state = {
        text: ``
    }
    componentDidMount() {
    if(this.props.text) this.setState({text: this.props.text})
}
    render() {
        const textBlock = document.getElementById("description");
        if (textBlock) return textBlock.innerHTML = this.state.text
    }    
}