如何将JavaScript变量的内容插入html中的特定位置?

时间:2019-06-20 15:28:46

标签: javascript html replace

给出以下代码:

<head><script>var label = "hello123";</script></head>
<body><h1>**[here]**</h1><p>This is the value: <span>**[here]**</span></body>

如何在指定位置插入var标签的值?

1 个答案:

答案 0 :(得分:1)

使用document.querySelector选择所需的元素,并将变量分配给其textContent,并循环遍历所选元素以更改其textContent

var label = "hello123";

document.querySelector('h1').textContent = label;

document.querySelector('span').textContent = label;
<body><h1></h1><p>This is the value: <span></span></body>

-编辑-

要通过className选择多个元素,请使用document.querySelectorAll

var label = "hello123";

document.querySelectorAll('.someClass').forEach((ele) => {
    ele.textContent = label;
});
<h1 class="someClass"></h1><p>This is the value: <span class="someClass"></span>