繁体   English   中英

如何根据数据属性更改元素值?

[英]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>

https://jsfiddle.net/9evue27z/

按文档定义 :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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM