Skip to content Skip to sidebar Skip to footer

Js Change All 'p' Color

i want to change color all 'p' elements, i tried do it with this code but it not works. document.getElementsByTagName('p').forEach(element => { element.style.color = 'white' })

Solution 1:

You can accomplish this using the vanilla JavaScript ES2015 (ES6) code.

document.querySelectorAll('p').forEach(e => e.style.color = "white");

UPDATE:

I forgot to mention that this is applying white color of the element in the DOM which is not so efficient, so you can also do this in another way.

CSS:

.white {
  color: #fff;
}

JavaScript:

// If you have just one class for the elementdocument.querySelectorAll('p').forEach(e => e.className = 'white');

// If you are appending the class of `white`document.querySelectorAll('p').forEach(e => e.className += ' white'); 

Solution 2:

You can't iterate over the HTMLCollection returned by getElementsByTagName. Converting it to an Array will work, though. Use Array.from() to do this:

Array.from(document.getElementsByTagName('p')).forEach(element => { element.style.color = 'white' });

Solution 3:

You can do the same like this

var list= document.getElementsByTagName('p');
for (var i = 0; i < list.length; i++) {
    list[i].style.color = "white";
}

As document.getElementsByTagName returns HTMLCollection type object you have to iterate using above method as per this answer

Solution 4:

All you have to do here is to make a simple loop.

let el = document.getElementsByTagName('p')
let i

for (i = 0; i < el.length; i++) {
    el[i].style.color = 'white'
}

Solution 5:

document.getElementsByTagName('p')

Return HTMLCollection(6) [p, p, p, p, p, p.left] This is a HTML Collection. So if you check

document.getElementsByTagName('p') instanceofArray

It returns false.

As HTML Collections are not array's so you cannot perform .forEach().

So you must convert it into an array by using Array.from().

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Array.from(document.getElementsByTagName('p')).forEach(element => {
 element.style.color = 'white'
});

So this is the solution for your problem.

Post a Comment for "Js Change All 'p' Color"