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.

1

3 Answers 3

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");
}
Sign up to request clarification or add additional context in comments.

5 Comments

or he could just use onclick="classAdd()" and reference this in the function, or would this be wrong due to some reason?
That won't work, this isn't passed when you call a function like that.
Alternative is to embrace jquery and set the event in the javascript instead of using onclick= - then you get this.
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...
@despamigros Use toggleClass instead of addClass.
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');
                                                 });
                          }

1 Comment

This will require two clicks. The first click adds the event listener, the second click adds the class.
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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.