Home » Jquery » javascript – jquery if $this has not ClassName do action

javascript – jquery if $this has not ClassName do action

Posted by: admin February 22, 2020 Leave a comment

Questions:

I see many answers but none of them seem to be working.

All my buttons have the “Trev” class. I want to check if the clicked class, also contains the “Namdons” class, and if so, do some code. However if not, do some code.

Some code that half works is:

$(".Trev").click
(
    function(e) 
    {

        if($(this).hasClass("Namdons")) 
        {
            console.log("Namdons");
        }
        else
        {
            console.log("Asdf");
        }
        e.preventDefault();

    }
);

However the “else” condition is not executing.

I’ve tried:

$(".Trev").click
(
    function(e) 
    {

        if($(this).hasClass("Namdons")) 
        {
            console.log("Namdons");
        }
        if(!$(this).hasClass("Namdons"))   //added apostrophe
        {
            console.log("Asdf");
        }
        e.preventDefault();

    }
);

as per these pages:

How to check if an element does NOT have a specific class?
How do I use hasClass to detect if a class is NOT the class I want?

The “not” command does not apply as I’m only wanting to procure a single element and not select a bunch of them. Explained more on those pages.

HTML:

<div class="Trev Width50" onclick="Button('buttonname')"></div>

and

<button onclick="Namdons()" class="Namdons Trev TextAlignCenter">ButtonTitle</button>

also tried changing the Width50 div to a button:

<button class="Trev Width50" onclick="Button('buttonname')"></button>

There also doesn’t seem to be an “elseif” in javascript is that correct?

Thanks.

How to&Answer:

Since you tag javascript i put example in vanilla js. I leave it for you to translate it to jQuery. I also put notes inside:

const trev = document.querySelectorAll('button.trev'); // get button with .trev style
for (var i=0; i < trev.length; i++) { // itterate them
  trev[i].addEventListener('click', function() { // add click event
    if (this.classList.contains('Namdons')) {alert('This is .Namdons');} // if it has .Namdons alert it
    else {alert('This is NOT .Namdons');} // it not alert that
  });
} 
<button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button>

Read more about classList on MDN