In javascript, how to get a class name from a td cell?
example:
<td class="ColumnHeader" style="text-align:right;" >
class "ColumnHeader" is a class inside css, how could i retrieve it from css and changed the width size in javascript?
In javascript, how to get a class name from a td cell?
example:
<td class="ColumnHeader" style="text-align:right;" >
class "ColumnHeader" is a class inside css, how could i retrieve it from css and changed the width size in javascript?
Share Improve this question edited Nov 15, 2011 at 2:35 Michael Berkowski 271k47 gold badges450 silver badges393 bronze badges asked Nov 15, 2011 at 2:32 C PWLC PWL 5196 gold badges10 silver badges26 bronze badges 1-
Are you trying to modify a stylesheet with JS or modify the
class
attribute of a DomNode? – fnp Commented Nov 15, 2011 at 2:36
2 Answers
Reset to default 7Select all the <td>
elements via getElementsByTagName()
and iterate over them looking for the className
:
var tds = document.getElementsByTagName("td");
for (var i = 0; i<tds.length; i++) {
// If it currently has the ColumnHeader class...
if (tds[i].className == "ColumnHeader") {
// Set a new width
tds[i].style.width = new_width;
// Or set a different class which defines the width
tds[i].className = "someOtherClass";
}
}
You can't really change the width of the css class programatically, but you can change it on the element:
td.style.width = newWidth;
To get the class name from an element, use:
var className = td.className;