jeudi 15 juillet 2021

Is it possible to change the class of an element if the class of another elements equals to sth?

I want to remove/add the classList of some element if the classList of another element is equal to "sth". But there is a little problem that it only runs the command once, I mean the condition doesn't check the classList of the first element every second so it runs it without any problem. If the if is true then it runs the if condition and then it won't check else if and so reverse.

Here is my code:

const dToggle = () => {
  const firstElm = document.querySelector('.firstElm');
  
  firstElm.classList.toggle('red-border');
};

document.querySelector('button').addEventListener('click', dToggle);

const orangeOrRed = () => {
    const firstElm = document.querySelector('.firstElm');
    const secondElm = document.querySelector('.secondElm');

    firstElm.classList === 'red-border' ? secondElm.classList.add('red') : secondElm.classList.add('orange');
    
    // if (firstElm.classList === 'red-border') {
    //        secondElm.classList.remove('orange');
    //        secondElm.classList.add('red');
    // } else if (firstElm.classList === 'orange-border' {
    //        secondElm.classList.remove('red');
    //        secondElm.classList.add('orange');
    // };
};

// Maybe the exact problem is right here.
window.addEventListener('load', orangeOrRed);

console.log(document.querySelector('.secondElm').classList.value);
.d-none {
  display: none !important;
}

.firstElm {
  margin-top: 10px;
  width: 200px;
  height: 100px;
  background-color: blue;
 }
 
.orange-border {
  border: orange 3px solid;
}
 
.red-border {
  border: red 3px solid;
}
 
.secondElm {
  margin-top: 10px;
  width: 200px;
  height: 100px;
  background-color: green;
}

.orange {
  background-color: orange !important;
}

.red {
  background-color: red !important;
}
<button type="button" style="cursor: pointer;">Click here.</button>
<p>It should run the conditional statement whenever I click on the button to apply the border.</p>
<p> First Elm Border Color (MUST BE) Second Elm Background Color</p>
<div class='firstElm orange-border'></div>
<div class='secondElm'></div>
<p style="padding-bottom: 10px;">Remember that I only want to do this with(conditioal statements), It's possible either with classList.toggle() but I don't want to.</p>

Aucun commentaire:

Enregistrer un commentaire