How can I prove my adding a class worked?

48 Views Asked by At

This is an easy one I'm sure but I can't find anything searching or on Google.

If I use

document.getElementById(someId).className += " whateverClass";

or

$('#').addClass('whateverClass');

How can I prove this in the console? (So that I know that step is working correctly)

4

There are 4 best solutions below

2
Sunny Patel On

Easy enough in jQuery by using .hasClass():

console.log( $('#someId').hasClass('whateverClass') );

You can execute this in your code or in the browser console itself.

0
mvc_help On

You can check in the inspector (Right Click -> Inspect Element) and see if the element has the class added, or you can do $("#selector") in the console and check through the properties returned.

Failing that, do something in the CSS class that will visually confirm it has been added (bold text, red outline, capital letters, etc..)

0
Isak Berglind On

jQuery has a method for that.

if( $('#test').hasClass('whateverClass') ) {
   // Awesome code..
}

https://api.jquery.com/hasclass/

1
SeeTheC On

In javascript, rightwa of add multiple class is

var el=document.getElementById(id);
el.classList.add("your-class");

NOT

document.getElementById(someId).className += " whateverClass";

In jquery, you can achieve this by simpily

$("#"+id).addClass("your-class");

You can check whether class is present or not

in jquery alert( $('#'+id).hasClass('your-class') )