-1

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?

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

5 Answers5

9

You can use

var firstClass = html.className.split(' ')[0]
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

An alternative way of getting the separated class names is by using classList. see browser support and documentation

Jakob W
  • 3,347
  • 19
  • 27
2
> "hey there".split(" ")[0]
"hey"
Claudiu
  • 224,032
  • 165
  • 485
  • 680
1
var classes = class.split(" "); // Returns an array
var firstclass = classes[0];
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
1

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.

Hugo Tunius
  • 2,869
  • 24
  • 32