Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript getting an elements class without any libraries

I would like to get the value of the class attribute for an element using JavaScript. However in this particular situation I don't have the luxury of library such as YUI, jQuery, etc. and need to stick to the basics.

Specifically, I am looping over a table and want to check the class of the cell.

I tried:

var colClass = el.getAttribute('class');

and

var colClass = el.class; 

But neither seems to be working. In the above example, el is set from cells array of a table, such as var el = document.getElementById('myTable').rows[y].cells[y];

like image 461
Aaron Silverman Avatar asked Aug 10 '10 21:08

Aaron Silverman


People also ask

Can you get element by class in JavaScript?

The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.

How do I get the class of an element in HTML?

To get the class names of a specific HTML Element as String, using JavaScript, get reference to this HTML element, and read the className property of this HTML Element. className property returns the classes in class attribute separated by space, in a String.

How do I grab an element by ID?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.


1 Answers

Maybe you should try this

var colClass = el.className 
like image 63
Bang Dao Avatar answered Sep 25 '22 11:09

Bang Dao