Home > other >  Change Text color of an ul with a Javascript button
Change Text color of an ul with a Javascript button

Time:11-17

I need to create a button to change my li's to black.

html

 <h2>Sonnenfarben</h2>
  <div >
     
    <ul type="circle" >
      <li >rot</li>
      <li >orange</li>
      <li >gelb</li>
    </ul>
    
    <button onclick="changeColor()">Lights out</button>

  <ol  start="3">
      <li >braun</li>
      <li >grau</li>
  </ol>

css

.farbeRot{
  color: ;
  font-weight: bold;
}

.farbeOrange{
  color: orange;
  font-style: italic;
}

.farbeGelb{
  color: yellow;
}

.farbeBraun{
  color: brown;
  font-style: italic;
}

.farbeGrau{
  color: grey;
  font-weight: bold;
}

.box{
  color: black;
}

JS

function changeColor(){
  document.querySelector('.box').style.color = "black";
}

Tried to connect everything but didn´t work out.

edit: put in all colors I defined already. Tried deleting them etc. but it still did not work.

CodePudding user response:

You need to change the default color of .box from black to other values,such as red or green

.box{
  color: red;
}

function changeColor(){
  let lis = document.querySelectorAll('.liste2 > li,liste3 > li');
  for(let i=0;i<lis.length;i  ){
    lis[i].style.color = "black";
  }
}
.farbeRot{
  color: green;
  font-weight: bold;
}

.farbeOrange{
  color: orange;
  font-style: italic;
}

.farbeGelb{
  color: yellow;
}

.farbeBraun{
  color: brown;
  font-style: italic;
}

.farbeGrau{
  color: grey;
  font-weight: bold;
}

.box{
  color: black;
}
<h2>Sonnenfarben</h2>
  <div >
     
    <ul type="circle" >
      <li >rot</li>
      <li >orange</li>
      <li >gelb</li>
    </ul>
   

  <ol  start="3">
      <li >braun</li>
      <li >grau</li>
  </ol>
  
   <button onclick="changeColor()">Lights out</button>
</div>

CodePudding user response:

if you just wanna change your li's color by a click event, don't do it that manually(almost). write a CSS-styled class for your ul and toggle it on click event

function changeColor() {
  const liste2 = document.querySelector(".liste2");
  liste2.classList.toggle("black-ul")
  
  /*
  if you just want the lights off and not toggle, replace above "toggle" with "add"
  simple javascript my boy
  */
  
}
.farbeRot{
  color: green;
  font-weight: bold;
}

.farbeOrange{
  color: orange;
  font-style: italic;
}

.farbeGelb{
  color: pink;
}

.farbeBraun{
  color: brown;
  font-style: italic;
}

.farbeGrau{
  color: grey;
  font-weight: bold;
}

.box{
  color: black;
}


/* below code is to make all the li black */

.black-ul > li {
  color: black
}
<div >
     
    <ul type="circle" >
      <li >rot</li>
      <li >orange</li>
      <li >gelb</li>
    </ul>
    
    <button onclick="changeColor()">Toggle light</button>
</div>

  • Related