0

I want to determine the class name of existing table TD elements (using the Chrome Javascript).

My case is table rows all like <tr><td class="ns"><a href="a link">a name</a><td> ...

I want to find that "ns" and others (they vary a little) to process some rows differently.

The easy assumed way would seem to be the className on cells[0], but in the Chrome debugger it is "" (blank) ... THiS IS AN INCORRECT STATEMENT

I found something like this next marked line. This was my interpretation:

for (let row = Obj.rowcnt - 1; row > 0; row--) {     
    let x0 = Obj.tbl,rows[row].cells[0];
    let clas = x0.constructor.name;         // <---<<
console.log(clas + "  " + x0.constructor.name);
... 

But I obviously interpreted it wrong, and all I see is "HTMLTableCellElement HTMLTableCellElement"

I don't find "constructor.name" in the table td elements.

EDIT:

Thank you, you hit it dead on. Some of my rows do have a "" className, and I got confused and mixed up and made the wrong conclusion on wrong row. I am in good shape now, thank you.

2
  • 1
    perhaps x0.className or x0.classList Commented Aug 18 at 1:20
  • Finding the class name is one thing, but what would you like to achieve? That is the use case? Commented Aug 18 at 5:38

1 Answer 1

2

If you are sure that there is only one CSS class, like ns in your example, use x0.className. Please see https://developer.mozilla.org/en-US/docs/Web/API/Element/className.

In more general case, you can have several CSS classes prescribed in HTML for your element. Then you can use x0.classList. Please see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList.

Your idea of using x0.constructor is based on a misconception. The constructor is a universal JavaScript concept totally unrelated to CSS classes. However, it has some semantic having something in common with the concept of a type or a class in the strictly typed languages with Reflection, but JavaScript concept is very different. Moreover, if your object was created using a JavaScript class constructor, its .constructor is exactly that class. You can use the object's constructor data property to check up types of different objects, even of the primitive types. However, in most cases, instanceof is better, please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.