Adding and removing styles from a particular selection at the click of a button

11

I have a function in javascript that applies a particular style in some classes, and I would like to know how to do 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;
    
asked by anonymous 26.11.2015 / 22:29

3 answers

12

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

Then you can create a function that adds and removes a class (this is called a 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, overriding the old one:

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;
}
    
26.11.2015 / 22:42
1

An alternative that follows the same logic as the first response, 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, however, using only CSS and with some limitations, such as the HTML structure hierarchy, 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>
    
26.11.2015 / 23:39
0

Have a helper available. Here are a number 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+|$)');
  }
};
    
28.11.2015 / 13:31