How to change color to red of the first paragraph? HTML: <!DOCTYPE html> <html…
- User
How to change color to red of the first paragraph? HTML:
JS: const firstIntro = document.querySelector('.intro'); firstIntro.style.color = 'red';
- Assistant
Your JavaScript code is correct and will change the color of the first paragraph with the class
introto red.Explanation:
document.querySelector('.intro')selects the first element with the classintro.- Then you set the style property
colorto'red'.
When this JavaScript runs, the first
<p class="intro">Paragraph 1</p>will turn red.If you want to ensure it runs after the DOM has loaded, you can wrap your code in a DOMContentLoaded event:
document.addEventListener('DOMContentLoaded', () => { const firstIntro = document.querySelector('.intro'); firstIntro.style.color = 'red'; });Alternatively, place your script at the end of the
<body>before closing it so it runs after the DOM elements are available.
Summary:
Your current method:
const firstIntro = document.querySelector('.intro'); firstIntro.style.color = 'red';is the proper way to change the color of the first paragraph with class
introto red. - User
I use VS Code and Live Server but I don't have any changes with color
- Assistant
If you're not seeing the color change when using VS Code with Live Server, here are some common troubleshooting steps to help you:
1. Make sure your JavaScript is running after the DOM is loaded
Currently, your script is included in the
<head>:<script src="script.js"></script>This means the JS runs the HTML elements exist, so returns , and the style change does nothing.