Home > Back-end >  How do I change textcolor with a button in javascript?
How do I change textcolor with a button in javascript?

Time:05-28

I want to change a certain part of text, named "box" in html to a different color when a button "btn" is clicked with javascript.

But I get the error "Uncaught TypeError: Cannot read properties of undefined (reading 'style')".

Here's what I did in js:

const btn = document.getElementById('btn');
const box = document.getElementById('box');

btn.addEventListener('click', function onClick(event) {
  document.box.style.color = 'black';
});

I checked different websites and for other instances, this code seems to work. Can anyone tell me where I went wrong? Thanks!

CodePudding user response:

correct the fourth line of your code to

box.style.color = 'black';

CodePudding user response:

const btn = document.getElementById('btn');
const box = document.getElementById('box');

btn.addEventListener('click', function onClick(event) {
  box.style.color = 'blue';
});
<button id = "btn">Click Me</button>
<p><span id = "box">Some text.</span> Some more text.</p>

You don't need to put document. You only put the element/variable.style.property = "value" Document is a element of the file: <html> and you also can only put 1 element before the style.

CodePudding user response:

You've got a small mistake. I have adjusted it.

  1. You already fetch the box in a variable (box)
  2. you can pass to the eventListener an anonymous function

const btn = document.getElementById('btn');
const box = document.getElementById('box');

btn.addEventListener('click', (event) => {
   box.style.color = 'red';
});
<div id="box">123</div>
<button id="btn">Change</button>

CodePudding user response:

The issue was the last line of your sample code shouldn't have document at the beginning. It's also missing the closing curly brace and semi-colon but I'm assuming that's further down in your code and you only gave a snippet.

Other than that I want to suggest you use click delegation on the document body. This way you can have a single click listener which you can then add more checks to

document.body.addEventListener('click', e => {
    e.target.id = 'btn' && ( document.getElementById('box').style.color = 'black' );
}, false);

In the above code we add a click event listener to the document body (the <body> tag in HTML). Then in the listener we check if the target's ID is equal to btn, and if this matches we change the element with ID of box

If this looks a little weird it's a more succinct way to write the following

document.body.addEventListener('click', e => {
    if (e.target.id = 'btn') {
        document.getElementById('box').style.color = 'black';
    }
}, false);

You could still set #btn and #box as constants if you like

  • Related