Add and remove styles of a particular selection by clicking a button

Asked

Viewed 1,147 times

11

I have a javascript function that applies a certain style in some classes, and would like to know how to take this style by clicking the same button.

var botao = document.getElementById("troca");
var cores = document.getElementsByClassName("cores");

function aplicaCores() {
   for (var i = 0; i < cores.length; i++) {
      cores[i].style.background = "red";
      }
   }

botao.onclick = aplicaCores;

3 answers

12


Create CSS classes that apply these colors instead of applying them directly to HTML.

And then you can create a function that adds and removes a class (this is called toggle):

var botao = document.getElementById("troca");
var cores = document.getElementsByClassName("cores");

function aplicaCorVermelha() {
  for (var i = 0; i < cores.length; i++) {
    cores[i].classList.toggle('red');
  }
}

botao.onclick = aplicaCorVermelha;

CSS:

.red {
    background-color: red;
}

Or a function that adds a given class, superimposing on the old:

var verde = document.getElementById("green");
var vermelho = document.getElementById("red");
var cores = document.getElementsByClassName("cores");

function aplicaCor() {
  var cor = this.id
  for (var i = 0; i < cores.length; i++) {
    cores[i].className = cor;
  }
}

verde.onclick = aplicaCor;
vermelho.onclick = aplicaCor;

CSS:

.red {
    background-color: red;
}
.green {
    background-color: green;
}
  • Sergio: helped me a lot the solution of putting cores[i].classList.toggle('red');

1

An alternative that follows the same logic as the first answer, but with a different syntax:

document.getElementById("toggle").addEventListener('click', function() {
    Array.prototype.forEach.call(document.getElementsByClassName('select'), function(elementos) {
    	elementos.classList[elementos.className.indexOf('selected') === -1 ? 'add' : 'remove']('selected');
    });
});
.selected {
    background-color: red;
}
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<button id="toggle">toggle</button>

Another alternative as well, but using only CSS and with some limitations, such as the hierarchy of the HTML structure, is:

input[type=checkbox]:checked ~ .select {
    background-color: red;
}
<label for="toggle">Select</label>
<input type="checkbox" id="toggle" value="">


<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<p class="select">texto</p>
<div>
    <p class="select">Não vai ficar selecionado se não for definido a hierarquia. Ex: <pre>input[type=checkbox]:checked ~ div > .select</pre></p>
</div>

  • In what way is this answer different from my first example? As I see it, you changed the method toggle by a ternary elementos.className.indexOf('selected') === -1 ? 'add' : 'remove' that seems less semantic to me.

0

Have a helper at your disposal. Here are a lot of methods for manipulating CSS classes. Some possibilities:

utils.toggleClass(div, 'red');
utils.addClass(div, 'red blink');
// utilizando timeout
utils.addClass(div, 'red tooltip', 2000);
utils.removeClass(array_div, 'hidden');

var utils = {
  /**
   * @param {Element|Array<Element>} element DOM node ou array de elementos.
   * @param {String|Array<String>} classname Classe ou array de classes.
   * Por exemplo: 'class1 class2' ou ['class1', 'class2']
   * @param {Number|undefined} timeout Timeout para remover a classe (opcional).
   */
  addClass: function(element, classname, timeout){
    if(Array.isArray(element)){
      element.forEach(function(each){
        utils.addClass(each, classname);
      });
      return;
    }

    var 
      array = (Array.isArray(classname)) ? classname : classname.split(/\s+/),
      i = array.length
    ;
    while(i--){
      if(!utils.hasClass(element, array[i])) {
        utils._addClass(element, array[i], timeout);
      }
    }
  },
  _addClass: function(el, c, timeout){
    // preferência para `classList` se nativo
    if (el.classList) {
      el.classList.add(c);
    } else {
      el.className = (el.className + ' ' + c).trim();
    }

    if(timeout && utils.isNumeric(timeout)){
      win.setTimeout(function(){
        utils._removeClass(el, c);
      }, timeout);
    }
  },
  /**
   * @param {Element|Array<Element>} element DOM node ou array de elementos.
   * @param {String|Array<String>} classname Classe ou array de classes.
   * Por exemplo: 'class1 class2' ou ['class1', 'class2']
   * @param {Number|undefined} timeout Timeout para adicionar a classe (opcional).
   */
  removeClass: function(element, classname, timeout){
    if(Array.isArray(element)){
      element.forEach(function(each){
        utils.removeClass(each, classname, timeout);
      });
      return;
    }

    var 
      array = (Array.isArray(classname)) ? classname : classname.split(/\s+/),
      i = array.length
    ;
    while(i--){
      if(utils.hasClass(element, array[i])) {
        utils._removeClass(element, array[i], timeout);
      }
    }
  },
  _removeClass: function(el, c, timeout){
    if (el.classList){
      el.classList.remove(c);
    } else {
      el.className = (el.className.replace(utils.classRegex(c), ' ')).trim();
    }
    if(timeout && utils.isNumeric(timeout)){
      win.setTimeout(function() {
        utils._addClass(el, c);
      }, timeout);
    }
  },
  /**
   * @param {Element} element DOM node.
   * @param {String} classname Classe.
   * @return {Boolean}
   */
  hasClass: function(element, c) {
    // preferência para `classList` se nativo
    return (element.classList) ?
      element.classList.contains(c) : utils.classRegex(c).test(element.className);
  },
  /**
   * @param {Element|Array<Element>} element DOM node ou array de elementos.
   * @param {String} classname Classe.
   */
  toggleClass: function(element, classname){
    if(Array.isArray(element)) {
      element.forEach(function(each) {
        utils.toggleClass(each, classname);
      });
      return;
    }

    // preferência para `classList` se nativo
    if(element.classList) {
      element.classList.toggle(classname);
    } else {
      if(utils.hasClass(element, classname)){
        utils._removeClass(element, classname);
      } else {
        utils._addClass(element, classname);
      }
    }
  },
  isNumeric: function(str){
    return /^\d+$/.test(str);
  },
  classRegex: function(classname) {
    return new RegExp('(^|\\s+)' + classname + '(\\s+|$)');
  }
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.