簡體   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