skip to Main Content

i want to change multiple color in my website .but how ? my webstite body bg color changed good ,but i can’t change section background-color .Help me

iam trying to some javascrip body bg-color change.it worked but i want to change my section bg-color

2

Answers


  1. I don’t know if I understood it correct but can you try the code below.

     const btn = document.getElementById('my-btn');
     const section = document.getElementById('my-section');
     const colors = ["red", "green", "blue"];
     const colorIndex = 0;
        
     btn.addEventListener('click', function() {
         const newColorIndex = parseInt((Math.random() * (3 - 1) + 1).toFixed());
         section.style.backgroundColor = colors[newColorIndex - 1];
     });
     #my-section {
         height: 300px;
         border: 1px solid #000;
     }
            
     #my-btn {
         margin-bottom: 10px;
     }
    <button id="my-btn">Click Me</button>
    <div id="my-section"></div>
    Login or Signup to reply.
  2. Considering you want to change background of element with id=outer-section.

    HTML:

    <section id="outer-section">
        <section id="inner-section">
        </section>
    </section>
    

    JS:

    document.getElementById("outer-section").style.background = "red"
    
    // or using parentElement
    document.getElementById("inner-section").parentElement.style.background = "red"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search