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'
});
Is there a right way(without using JQuery)?
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'
});
Is there a right way(without using JQuery)?
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 element
document.querySelectorAll('p').forEach(e => e.className = 'white');
// If you are appending the class of `white`
document.querySelectorAll('p').forEach(e => e.className += ' white');
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'
});
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'
}
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') instanceof Array
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.