1

I have something like this

public render(){

  let htmlRender = "<html><body><h2>Children</h2>Joe has three kids:<br/><ul><li>Linn Fenimore Cooper Cary (married writer <a href='Ved Mehta'>Ved Mehta</a> in 1983)</li><li>kid2</li><li>kid3</li></ul></body></html>";

  const doc  = new DOMParser().parseFromString(htmlRender,'text/html');


  let ele = doc.evaluate("/html/body/ul/li[1]/a[1]", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  ele.singleNodeValue.style.background = 'pink';

  return (
        <div className="details-block context-block">
            <h5>Context</h5>
            <div dangerouslySetInnerHTML={{__html:doc.body.toString()}} /> --> This returns [object HTMLBodyElement]
        </div>
    );
}

This is what I am doing above - Taking a html string converting it into a HTML object. Then parsing that using Xpath. Manipulating it(adding the color) and then I want to display it. But it appears as [object HTMLBodyElement]. what am I doing wrong?

Thanks for the help!

suprita shankar
  • 1,554
  • 2
  • 16
  • 47
  • try printing `doc.body.toString()` to console and see what you get. edit: yeah, `doc.body.toString()` -> "[object HTMLBodyElement]". Use `doc.body.innerHTML` – Tyler Sebastian Mar 20 '17 at 20:44

1 Answers1

1

I tried it out in Chrome's console and I think your issue is doc.body.toString().

> let x = "<html>...</html>";
> let y = new DOMParser().parseFromString(x, "text/html");
> y                 // #document
> y.body            // <body>​…​</body>​
> y.body.toString() // "[object HTMLBodyElement]"

Instead of toString(), use innerHTML (or outerHTML if you want the <body/> tags).

> y.body.innerHTML  // "<h2>Children</h2> ..."

What's happening is you are creating a React div element with the literal string contents "[object HTMLBodyElement]" instead of the contents of doc.body - doc.body.innerHTML

edit: according to comments here you should actually be using new XMLSerializer().serializeToString(document) - up to you; whatever works.

Community
  • 1
  • 1
Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62