scatta678
scatta678

Reputation: 17

getElementsByClassName returns class names that contain specified name

I am using document.getElementsByClassName('example'), but it also returns classes where the specified parameter is a substring. For example, it would also return an element where the classname is 'other example'. Is there a way to fix this?

Upvotes: 1

Views: 7099

Answers (2)

Joel Banzatto
Joel Banzatto

Reputation: 147

If your element class name is "other example" it means that your element has 2 classes. Try to name your classes with '-' or "_" like "other_example" or "other-example".

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

There's nothing broken; you're selecting for any elements with the "example" class. class="other example" means an element has both "example" and "other".

If you want to retrieve elements with only one class, and your browser supports querySelectorAll*, you can use that, like so:

var exact = document.querySelectorAll('[class="example"]');

for ( var i = 0; i < exact.length; ++i )
  exact[i].style.fontWeight = 'bold';
<p class="example">example only</p>
<p class="other example">... and other</p>

* Which it does, if it also supports getElementsByClassName

Upvotes: 7

Related Questions