-1

JQuery code is very simple:

$('.nav-menu').on('click','li', function(){
    $(this).addClass('selected').siblings().removeClass('selected');

upon click it adds class selected to selected .nav-menu element and removes that selected class from all siblings.

Best and shortest way to do exact the same with pure JavaScript?

Possible duplicate is Not a solution

I need not just to add specific class. But also to remove that same class from all siblings of element.

Related HTML:

        <ul id="tabnav" class="nav-menu">
            <li class="tab selected"><a href="#">Element 1</a></li>
            <li class="tab"><a href="#">Element 2</a></li>
            <li class="tab"><a href="#">Element 3</a></li>
        </ul>
Community
  • 1
  • 1
SavageStyle
  • 61
  • 1
  • 11
  • Possible duplicate - http://stackoverflow.com/questions/6787383/how-to-add-remove-a-class-in-javascript – Tricky12 Apr 17 '17 at 14:57
  • Possible duplicate of [How to add/remove a class in JavaScript?](http://stackoverflow.com/questions/6787383/how-to-add-remove-a-class-in-javascript) – Junius L Apr 17 '17 at 15:00
  • it is not duplicate, I have explained better. You also point me to very same answer. – SavageStyle Apr 17 '17 at 15:29

2 Answers2

0

Pure JavaScript? Then the JS code will look this for me:

function addClass(el, className) {
  if (el.classList)
    el.classList.add(className)
  else if (!hasClass(el, className)) el.className += " " + className
}

function removeClass(el, className) {
  if (el.classList)
    el.classList.remove(className)
  else if (hasClass(el, className)) {
    var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
    el.className=el.className.replace(reg, ' ')
  }
}
haMzox
  • 2,073
  • 1
  • 12
  • 25
-1

Modern browsers have added classList:

document.getElementById('id').classList.add('YourClass'); //add
document.getElementById('id').classList.remove('YourClass'); //remove

Note: Not supported in IE <= 9 or Safari <=5.0

steffanjj
  • 881
  • 9
  • 10