Yes Chef Studio

Get class name from element

A nice little script that will return the first class applied to an element. It's part of our internal slider code, but has lots of uses when other js libraries are involved.

 <script> 

function getFirstWord(element) {
    // Get the class name of the element
    let str = element.className;
    
    // Trim any leading or trailing spaces from the string
    str = str.trim();
    
    // Find the first space in the string
    const spaceIndex = str.indexOf(' ');
    
    if (spaceIndex === -1) {
        // If there are no spaces in the string, return the whole string
        return str;
    }
    
    // If there is a space in the string, return the substring before the space
    return str.substring(0, spaceIndex);
}


</script>