Gion Rubitschung
Gion Rubitschung

Reputation: 802

How can I get the class name with jQuery or Javascript

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.

Upvotes: 0

Views: 59

Answers (3)

Bijay Yadav
Bijay Yadav

Reputation: 958

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");
}

Upvotes: 0

Josh
Josh

Reputation: 11

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');
                                                 });
                          }

Upvotes: 0

Barmar
Barmar

Reputation: 780688

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");
}

Upvotes: 1

Related Questions