Reputation: 453
I've tried using textContent and innerHTML, but haven't been able to change hello world to goodbye.
<div data-test='hello'>
hello world
</div>
var test = document.querySelectorAll("[data-test='hello']");
//test.textContent = "goodbye";
test.innerHTML = "goodbye";
Upvotes: 0
Views: 37
Reputation: 1415
If there is a possibility of having more than one element with data-test
, you can still use 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");
Upvotes: 1
Reputation: 1697
Definition by documentation: The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.
The querySelectorAll
method return an array
, then you can change the first element as follow:
var test = document.querySelectorAll('[data-test="hello"]');
test[0].innerHTML = "goodbye";
<div data-test='hello'>
hello world
</div>
Upvotes: 1
Reputation: 1108
Change querySelectorAll to 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/
Upvotes: 1