I have the following:
var html = document.documentElement;
var class = html.className;
This returns "black ng-scope";
How can I make it so that class just returns the first word?
I have the following:
var html = document.documentElement;
var class = html.className;
This returns "black ng-scope";
How can I make it so that class just returns the first word?
An alternative way of getting the separated class names is by using classList
. see browser support and documentation
var classes = class.split(" "); // Returns an array
var firstclass = classes[0];
Another idea is using regular expressions if you could have other word boundaries than space.
var reg = /(.+?)(?:\s|$)/,
match = html.className.match(reg);
if (match) {
match[1]; // Your match
}
This has the added benefit of matching more than a single space.
EDIT: If you are using this to strictly get all classes of an HTML element and you are targeting sufficiently new browsers use classList
like Jakob W suggested.