0

I want to find with Javascript an element by class name. This class is unique. I try to do this with var element = document.getElementByClassName('uniqueclass')

This element have two classes (uniqueclass and element-x). I want to get the other class and work with this class as String. I tried this with various functions (classname.split, ...), but I don't find a solution.

Can anybody help me? Thanks!

  • http://stackoverflow.com/a/1227309/4361743 – karman Mar 25 '17 at 08:46
  • Possible duplicate of [Get class list for element with jQuery](http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery) – LuFFy Mar 25 '17 at 09:00

2 Answers2

0

You can fetch the node, retrieve the classList of the node and filter them by your term:

var uniqueClassName = 'unique'; // What is your unique className?

var element = document.querySelector('.' + uniqueClassName); // Fetch the element
var filterClassList = function (class) {
  return class !== uniqueClassName; // Differs the className from the unique one?
};

var classList = element.classList.filter(filterClassList); // Filter the classList via filter function
0

You are doing it in right way.

Few changes

element = document.getElementsByClassName('uniqueclass')[0];

It is Elements not Element and it return a HTML Collection. Since this class name is unique, use index [0].

To get other classses of this element,

class = element.getAttribute('class');

Now class contains "uniqueclass element-x"

Sagar V
  • 12,158
  • 7
  • 41
  • 68