0

I have a small code where i want to

  1. check which class is on the element curently.
  2. change the curent class to the other class

html :

  <div class="text-area-box" id="text-area-box">
      <input type="text" name="" required="">
      <label>Titre</label>
  </div>

css:

 .text-area-box-active{
    position: relative;
  }
  .text-area-box {
    position: relative;
    display: none;
  }

js (not correct) just a way to show what i want to do :

if(curentClass = text_area_box)
  {
    element.classList.remove('text-area-box');
    element.classList.add('text-area-box-active');
  }
else{
    element.classList.remove('text-area-box-active');
    element.classList.add('text-area-box');
}

how can i make the correct javascript.

  • 1
    `curentClass = text-area-box` -> `curentClass === "text-area-box"` 1. use quotes for the string 2. Use `===` for comparison, `=` is assignment. See [What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)](https://stackoverflow.com/q/11871616) 3. It's much better to check for the existence of class with `.classList.contains()` – VLAZ Oct 14 '22 at 17:30
  • Is that just pseudo-code or is it meant to be JavaScript? `-` in JS denotes subtraction; I bet you neither `text`, `area`, or `box` is defined, let alone a number. – code Oct 14 '22 at 17:31
  • @VLAZ i corrected it , the thing is that i don't know how to get the curentClass correctly, i have done so just as an exemple. – bilel abdelmoula Oct 14 '22 at 17:32

1 Answers1

-1

You can do this by getting element using JavaScript and then by using classList.contains() you can check whether this element contains a particular class or not.

//JavaScript to handle logic

function updateClass(){
//get element to get, compare and update class
 var element = document.getElementById("text-area-box");


 //classListApi to chek if this element has class 
 
 if(element.classList.contains('text-area-box'))
  {
 
    element.classList.remove('text-area-box');
    element.classList.add('text-area-box-active');
  }
else{
 
    element.classList.remove('text-area-box-active');
    element.classList.add('text-area-box');
}
  
  
}
//Call this functions according to your condition
 updateClass()
//adding colors for testing
.text-area-box{
background-color:red !important;
}

.text-area-box-active{
background-color:yellow !important;
}
<div class="text-area-box" id="text-area-box">
      <input type="text" name="" required="">
      <label>Titre</label>
  </div>
Saad Abbasi
  • 745
  • 11
  • 25
  • You're setting `curentClass` to `'text-area-box'` in the `if` condition; see the first comment on the question. Also, it is recommended to use the `classList` interface for interacting with the `class` attribute. Finally, adding an explanation to code (such as why certain choices were made, how the code solves the OP's issue) is always preferrable to just a dump of code. – Heretic Monkey Oct 14 '22 at 17:46