+ 2
Javascript : change the style of an element
var i = document.querySelectorAll('p'); i.style.color = 'red'; https://code.sololearn.com/WYJxz86DKKs0/#js very simple, but it doesn't work on sololearn. The error displays: TypeError: i.style is undefined. Where is the problem?
8 Answers
+ 5
Because querySelectorAll returns a NodeList, you need to use for loop to loop over the NodeList.
For example,
let pElems = document.querySelectorAll("p");
for (let i = 0; i < pElems.length; i++) {
pElems[i].style.color = "red";
}
+ 4
shubham kumar Please explain how the code you linked is answering this question?
+ 2
đKrishnađ€(đŽ) Your solution is for error message "cannot read property style of null"
+ 2
Wrap it an onload handler and loop through each paragraph
onload = function() {
var i = document.querySelectorAll('p');
for(p of i) p.style.color = 'green';
}
//Or go declarative
onload = () => {
document.querySelectorAll('p')
.forEach(p => p.style.color = 'green');
}
+ 2
Thanks for the answers. really I need to make a loop and the onload function. two Ore's solutions work perfectly. Grand merci
+ 1
var i = document.querySelectorAll('p');
i[1].style.color = 'green';
+ 1
Use the style attribute ...
0
It now depends on front person who is asking the question to solve by looking into my code for answer.