Check if CSS class exists without jQuery

Using vanilla javascript or prototype can show me how I can run validation to see if a class exists? For example, I add a class called hideIt with this code:

var overlay = document.getElementById("overlay_modal"); overlay.className += " hideIt"; 

I also need a script that can later check if hideIt exists. I tried things like:

 if (overlay.className == "hideIt") 

But this is not good. Any ideas?

+6
source share
4 answers

Use regexp . \b will match word boundaries (space, newline, punctuation, or end of line).

 var overlay = document.getElementById("overlay_modal"); if (overlay.className.match(/\bhideIt\b/)) { // frob a widget } 
+6
source

You can use getElementsByClassName() , although this is not supported in all browsers (not in IE and 9):

 if (!document.getElementsByClassName('classname').length){ // class name does not exist in the document } else { // class exists in the document } 

Depending on your browser compatibility requirements, you can use querySelectorAll() :

 if (document.querySelectorAll('#overlay_modal.hideIt')) { // the element with id of overlay_modal exists and has the class-name 'hideIt' } 

Literature:

+4
source
 var id = document.getElementById("id"); var classes = id.className.split(" "); if(classes.indexOf("class_name") == -1) { } 
+3
source

Since the question is asked here, the prototype path ,

 if (overlay.hasClassName('hideIt')) 
+3
source

Source: https://habr.com/ru/post/903224/


All Articles