alloohaa
alloohaa

Reputation: 53

adding and removing classname with eventlistener

I am trying to set eventlistener to a button

<button id="btn">click me</button>

document.getElementById('btn').addEventListener('click', function (e) {
test(e.target);
}, false);

And each time click is triggered, the other HTML element(.random ul) will get a new class of my class or remove it(on the second click)

function test() {
document.querySelector(".random ul").className = document.querySelector(".random ul").className += ' newclass'
    ? '' //need to remove the newclass
    : ''; //need to add the newclass
}

This obviously not working. I also found the following script to properly remove added classname:

document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/g , '' )
//from: http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript

I really don't know how to make it work and would like to ask you to help me with it please.

Upvotes: 1

Views: 95

Answers (2)

fboes
fboes

Reputation: 2239

I applaud you for not using jQuery. Some time ago I took the dive myself. This script may solve your problem, even for very old browsers:

function toggleClass (el, className) {
  if (el.classList) {
    el.classList.toggle(className);
  } else {
    if (el.className.match(new RegExp('(^|\\s)'+className+'(\\s|$)','g'))) {
      el.className = el.className.replace(new RegExp('\\s?' + className), '');
    }
    else {
      el.className += ((el.className !== '') ? ' ' : '') + className;
    }
  }
}


document.getElementById('btn').addEventListener('click', function (e) {
  toggleClass(document.querySelector('.random ul'), 'newclass');
}, false);
.newclass { color: red; }
<button id="btn">click me</button>

<div class="random">
  <ul>
    <li>Test</li>
  </ul>
</div>

Oh, and for more Vanilla-JS-stuff, get inspired by http://youmightnotneedjquery.com/ or my personal experiments at https://github.com/fboes/js-toolshed/blob/master/src/js-toolshed.js

Upvotes: 1

nils
nils

Reputation: 27174

In all modern browsers (IE 10+), you could use classList and its toggle method:

document.getElementById('btn').addEventListener('click', function (e) {
    test(e.target); // not sure why you need e.target?
}, false);

function test() {
    document.querySelector('.random ul').classList.toggle('newclass');
}

toggle works like jQuery's toggle.

Upvotes: 1

Related Questions