[英]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:我正在尝试读取保存为字符串值的 html 标记的 innerHtml,如下所示:
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如何使用document.getElementById("demo")
然后显示值getElementById() 方法
You can use a DOMParser
to convert your text into an HTMLDocument that you can use getElementById
on:您可以使用DOMParser
将文本转换为HTMLDocument ,您可以使用getElementById
:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.