[英]How to insert the contents of a JavaScript variable into specific positions in html?
Given the following code: 给出以下代码:
<head><script>var label = "hello123";</script></head>
<body><h1>**[here]**</h1><p>This is the value: <span>**[here]**</span></body>
How can I insert the value of the var label in the indicated positions? 如何在指定位置插入var标签的值?
select the required elements using document.querySelector
and assign the variable to it's textContent
and loop through the selected elements to change its textContent
. 使用
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>
-- Edit -- -编辑-
In order to select multiple elements by className use document.querySelectorAll
. 为了通过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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.