简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM