如何将JavaScript变量的内容插入html中的特定位置?
给定以下代码:如何将JavaScript变量的内容插入html中的特定位置?,javascript,html,replace,Javascript,Html,Replace,给定以下代码: <head><script>var label = "hello123";</script></head> <body><h1>**[here]**</h1><p>This is the value: <span>**[here]**</span></body> var label=“hello123”; **[此处]***这是值:*[此处]**
<head><script>var label = "hello123";</script></head>
<body><h1>**[here]**</h1><p>This is the value: <span>**[here]**</span></body>
var label=“hello123”;
**[此处]***这是值:*[此处]**
如何在指定位置插入var标签的值?使用
document.querySelector
选择所需的元素,并将变量分配给它的textContent
,并循环选择的元素以更改其textContent
var label=“hello123”;
document.querySelector('h1')。textContent=标签;
document.querySelector('span')。textContent=标签代码>
这是值:
Nice,我不知道textContent
。他们是否应该将
标签放在正文的末尾?我猜,如果他们从
标记执行此操作,它将不起作用。将脚本放置在head标记中意味着您没有等待DOM
加载,因此当您尝试访问尚未加载的html元素时,将出现错误。因此,脚本标记通常放在body标记的末尾之前,或者您可以将脚本放在head标记中,但是您需要将脚本代码包装在事件中,如DOMContentLoaded
-是的,原始海报的代码在头部有其
标记。那么应该在类标记项上替换文本吗?类似:这是值:在这种情况下,按类名document.querySelector('.here1').textContent=label选择元素
和document.querySelector('.class1')。textContent=label代码>