0

In my script I need to check if my newly created object inherits from a specific class. Found out this:

Check if an element contains a class in JavaScript?

I have tried to implement like this:

class Testing {

}

let test = new Testing();
let elem = document.getElementById("result");
try {
  elem.innerHTML = test.classList.contains("Testing");
} catch (e) {
  elem.innerHTML = e;
}
<span id="result">...</span>

Unfortunately, it's not working. Please help me find a solution.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Radek_pl
  • 107
  • 1
  • 5
  • 1
    `.classList` isn't a property of your `Testing` class. What class are you trying to check that it's a sub-class of? – Nick Parsons Oct 16 '19 at 11:56
  • 1
    A Javascript class is not the same as a HTML class attribute. – Keith Oct 16 '19 at 11:56
  • `classList` is a property of an HTMLElement ... class Testing isn't one of those – Bravo Oct 16 '19 at 11:57
  • 2
    Your most likely after `test instanceof Testing`.. – Keith Oct 16 '19 at 11:58
  • In my script there are more classes and a special static class. In the static class I want to push objects via a static method where I need to check if objects inherit from a specific class. In this simple code I need to check if these objects inherit from "Testing". – Radek_pl Oct 16 '19 at 12:00

1 Answers1

0

Your class definition is empty, so obviously your test object doesn't have any property called classList, this is why you're getting this undefined error.

Otherwise, you could simply check if test is an object of the Testing class this way :

if (test instanceof Testing) {
  //do something
}
Reqven
  • 1,688
  • 1
  • 8
  • 13