Home > Mobile >  Can't access element's class to change its name in JavaScript
Can't access element's class to change its name in JavaScript

Time:06-09

I'd like to change an element's class from score -box1 to score -box1.-active. I created a const $target to try to access the class score -box1 but its not working.

const $target = document.getElementByClassname('score -box1')
function PlayerScore(score = 0){
    if(score == 1){
        $target.toggle('-active');
    }else if(score == 2){
        $target.toggle('-active');
    }else if(score == 3){
        $target.toggle('-active');
    }

    return( /*html*/
    `
        <div class = "container">
            <div class = "score -box1">one</div>
            <div class = "score -box2">two</div>
            <div class = "score -box3">three</div>
        </div>
    `
    )
}

CodePudding user response:

The proper method is .querySelectorAll and it returns a node list , if you add a [0] at the end like below, you will get the first element of that node list (which maybe what you want for now), but if you want all target elements use a for loop to loop over document.querySelectorAll('score -box1') array.

const $target = document.querySelectorAll('score -box1')[0]
function PlayerScore(score = 0){
    if(score == 1){
        $target.toggle('-active');
    }else if(score == 2){
        $target.toggle('-active');
    }else if(score == 3){
        $target.toggle('-active');
    }

    return( /*html*/
    `
        <div class = "container">
            <div class = "score -box1">one</div>
            <div class = "score -box2">two</div>
            <div class = "score -box3">three</div>
        </div>
    `
    )
}

CodePudding user response:

As you are using react you could play with jsx:

Here an example how you could do it:

function PlayerScore(score = 0) {
  return (
    <div className="container">
      <div className={`score-box1 ${score === 1 ? '-active' : ''}`}>one</div>
      <div className={`score-box2 ${score === 2 ? '-active' : ''}`}>two</div>
      <div className={`score-box3 ${score === 3 ? '-active' : ''}`}>three</div>
    </div>
  );
}

as you see you don't need to use the target to get what you want

  • Related