0

I want to make a Javascript function where it reads the class of the selected element and adds the class active. How can I get the class of the HTML element where my function is?

I tried to make an Javascript function with document.getElementsByClassName(class), but that doesn't work.

function menuicon(){
  var className = $('div').attr('class');
  className.$(className).addClass("active");
}
<section class="menubar">
  <div class="menuicon" onclick="classAdd()">
    <span></span>
    <span></span>
    <span></span>
  </div>
</section>

<section class="home">
  <button class="hbutton" onclick="classAdd()"></button>
</section>

I want that the Javascript function reads out the class of the HTML element where the function is placed in.

Timisorean
  • 1,388
  • 7
  • 20
  • 30
Gion Rubitschung
  • 741
  • 11
  • 31
  • Either [What do querySelectorAll and getElementsBy* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) or [jQuery Learning Center](https://learn.jquery.com) – Andreas Jan 21 '19 at 17:19

3 Answers3

1

You need to pass the element to the function:

onclick="classAdd(this)"

Then in the function, you just use .addClass, you don't need to use className.

function classAdd(element) {
    $(element).addClass("active");
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • or he could just use `onclick="classAdd()"` and reference `this` in the function, or would this be wrong due to some reason? – Dellirium Jan 21 '19 at 17:30
  • 1
    That won't work, `this` isn't passed when you call a function like that. – Barmar Jan 21 '19 at 17:31
  • Alternative is to embrace jquery and set the event in the javascript instead of using `onclick=` - then you get `this`. – freedomn-m Jan 21 '19 at 17:35
  • can set the event even without jQuery sicne it is embracing good coding practices, I am baffeled that after three years of `.js` I never figgured out that `.onclick` is not equal to writting onclick inside HTML in this way... – Dellirium Jan 21 '19 at 17:37
  • @despamigros Use `toggleClass` instead of `addClass`. – Barmar Jan 21 '19 at 17:49
0

This code snippet only include 'active' in the classList of the div

var classAdd = function() {
                  var menuIcon = document.querySelector('div.menuicon');
                      menuIcon.addEventListener('click',() => {
                                                    menuIcon.classList.add('active');
                                                 });
                          }
Josh
  • 11
  • 4
  • This will require two clicks. The first click adds the event listener, the second click adds the class. – Barmar Jan 21 '19 at 17:32
0

If encase you want to stick with the div and the menuicon class. Below code will work fine for you.

function classAdd() {
    $("div.menuicon").attr("class", "menuicon active");
}
Bijay Yadav
  • 928
  • 1
  • 9
  • 22