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!
correct the fourth line of your code to
box.style.color = 'black';
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.
You've got a small mistake. I have adjusted it.
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>