I have this element:
<input id="Nombre" class="clase1 clase2 clase3" type="text" />
in JavaScript I can get the element like this:
var item = document.getElementById("Nombre");
Now how can I know if the element "item" contains the class "clase2"
That is, how can I know if an element has a class?
You can use the (read-only) property
classList
, which returns a string with the different classes separated by spaces (as they would be in yourHTML
):It has some useful methods, such as
contains( )
:List of supported methods:
If what you want is to make a conditional based on whether or not an element has a class you can do this very quickly:
There are several ways to see the class of an element, even the previous answers are quite good, but if you want to expand the options when solving the problem, here are some (although they may be repeated with some other answers).
In Javascript with
.className
you can see all the classes that an element has as a String.In a different way you can use
.classList
or.classList.value
as I explained beforeA different option would be to use
.contains
to verify with Booleans if it is true or not that it has the class that is being searched for .Another option you have is to use a combination of properties mentioned above, for example:
if you want to use the this attribute of an element you give it focus
it worked for me to validate fields with class