Javascript : change the style of an element | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

23rd Jul 2020, 4:17 PM
Irina
Irina - avatar
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"; }
23rd Jul 2020, 4:25 PM
Gordon
Gordon - avatar
+ 4
shubham kumar Please explain how the code you linked is answering this question?
23rd Jul 2020, 4:28 PM
Gordon
Gordon - avatar
+ 2
😉Krishna🤘(📴) Your solution is for error message "cannot read property style of null"
23rd Jul 2020, 5:07 PM
Gordon
Gordon - avatar
+ 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'); }
23rd Jul 2020, 6:05 PM
Ore
Ore - avatar
+ 2
Thanks for the answers. really I need to make a loop and the onload function. two Ore's solutions work perfectly. Grand merci
24th Jul 2020, 12:16 PM
Irina
Irina - avatar
+ 1
var i = document.querySelectorAll('p'); i[1].style.color = 'green';
23rd Jul 2020, 7:58 PM
JaScript
JaScript - avatar
+ 1
Use the style attribute ...
25th Jul 2020, 3:52 AM
Sanjay Kamath
Sanjay Kamath - avatar
0
It now depends on front person who is asking the question to solve by looking into my code for answer.
23rd Jul 2020, 5:08 PM
shubham kumar
shubham kumar - avatar