Search code examples
javascripthtmlvariables

How do I use Document method getElementById() on a html variable


I'm attempting to read the innerHtml of a html tag that is saved as a string value like so:

let htmlVar=`
<!DOCTYPE html>
 <html>
  <body>
   <h1>The Document Object</h1>
   <h2 id="demo">The getElementById() Method</h2>
  </body>
 </html>
`

How can I use document.getElementById("demo") and then display the value The getElementById() Method


Solution

  • You can use a DOMParser to convert your text into an HTMLDocument that you can use getElementById on:

    let htmlVar=`
    <!DOCTYPE html>
     <html>
      <body>
       <h1>The Document Object</h1>
       <h2 id="demo">The getElementById() Method</h2>
      </body>
     </html>
    `
    
    const parser = new DOMParser()
    const doc = parser.parseFromString(htmlVar, "text/html");
    console.log(doc.getElementById('demo').textContent)