Why this code is not running in JS?

const changeBgRed = () => {   document.body.firstElementChild.style.background = "red" }   

Welcome to Replit Ask @muskan07072000v!

Could you please send the full code that fails to run? The line you sent here appears to be correct.

2 Likes

Yes sure,…Here it is …
In index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>PortFolio Website</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <nav>
    <ul>
      <li>Home</li>
      <li>about me</li>
      <li>Hire Me</li>
    </ul>
  </nav>
  <div>
    <p> Hey I am a good boy </p>
  </div>
  <script src="script.js"></script>
</body>

</html>

In script.jss…


const changeBgRed = () => {
  document.body.firstElementChild.style.background = "red"
}

let b = document.body
console.log("First child of b is: ", b.firstChild)
console.log("First Element child of b is: ", b.firstElementChild)

This is not working the main which I have writteb earlier.

Incase this info is not sufficient here is the link to my replit
https://replit.com/@muskan07072000v/34ElementOnlyNavigation#script.js

What exactly about the code is not working?

@muskan07072000v It seems like the function changeBgRed is never run. Simply put changeBgRed() at the end of your script and it’ll recolor your <nav> element to red, as needed.

Based on the original post, it appears that they can’t color the <nav> element.