[英]How do I change element value based on the data attribute?
我尝试使用textContent和innerHTML,但无法将Hello World更改为再见。
<div data-test='hello'>
hello world
</div>
var test = document.querySelectorAll("[data-test='hello']");
//test.textContent = "goodbye";
test.innerHTML = "goodbye";
将querySelectorAll更改为querySelector
<div data-test='hello'>
hello world
</div>
<script>
var test = document.querySelector("[data-test='hello']");
//test.textContent = "goodbye";
test.innerHTML = "goodbye";
</script>
按文档定义 :querySelectorAll()方法将文档中与指定CSS选择器匹配的所有元素作为静态NodeList对象返回。
querySelectorAll
方法返回一个array
,然后可以按如下方式更改第一个元素:
var test = document.querySelectorAll('[data-test="hello"]'); test[0].innerHTML = "goodbye";
<div data-test='hello'> hello world </div>
如果data-test
可能包含多个元素,则仍然可以使用document.querySelectorAll
。
var test = document.querySelectorAll("[data-test='hello']");
for (var i = 0; i <= test.length; i++) {
test[i].innerHTML = "goodbye";
}
// or using newer syntax
test.forEach(x => x.innerHTML = "goodbye");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.