简体   繁体   中英

How can I prove my adding a class worked?

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)

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.

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..)

jQuery has a method for that.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM