I'm trying to use a with js script on HTML to change the color of all the paragraphs in my document.
So far I have used:
<button type="button" onclick="document.getElementsByClassName('paragraph').style.color='white'">white Font all</button>
and also
<button type="button" onclick="document.getElementsByTagName('p').style.color='white'">white Font all</button>
but it doesn't seem to work. I want to change the color of all the paragraph fonts in my document to white, or any color. I used ID and it works fine for 1 paragraph, but I need all of them at the same time.
<button type="button" onclick="document.getElementsById('intro').style.color='white'">white Font Intro</button>
Thanks for any help!
CodePudding user response:
The issue is that ClassName and TagName return a collection of elements rather than a single element. You must loop through the collection to change the style of all elements.
<button type="button" onclick="changeColor('white')">White Font All</button>
<script>
function changeColor(color) {
const elements = document.getElementsByTagName('p');
for (let i = 0; i < elements.length; i ) {
elements[i].style.color = color;
}
}
</script>
CodePudding user response:
getElementsByClassName returns array not a single element.
a sample for you
// example 1
document.getElementsByClassName('paragraph').forEach(p => p.style.color = 'white');
// example 2
let p = document.getElementsByClassName('paragraph');
for(let i = 0; i < p.length; i ) {
p[i].style.color = 'white';
}