Skip to content Skip to sidebar Skip to footer

How To Get Class Name Through Javascript?

How do I get the class name through JavaScript using element name from classic HTML. Like:

Solution 1:

There are a lot of solutions. First to access element classname you use this code :

element.className

Next if you want to test if a classname exist inside the element list, you can test it with indexOf but you could have false positive. class "foo" is not present in the following element.className : "foobar foobuzz"

Best way is to use RegExp :

checkIfElementHasClassName(element, className) {
   return (newRegExp('^|\\s' + className + '\\s|$')).test(element.className);
}

Solution 2:

I just reversed my question to get the required output. Here by reading the class name,I am getting the element name using the below JS:

     var elementName = "";
        var dd = document.getElementsByClassName("CheckBox");
        for (i = 0; i <= dd.length - 1; i++) {
            if (elementName == "")
            { elementName = dd[i].name; }
            else
            {
                elementName = elementName + "," + dd[i].name;
            }
        }

Post a Comment for "How To Get Class Name Through Javascript?"