2010-08-10 14 views
32

我想獲得使用JavaScript的元素的屬性的值。然而,在這種特殊情況下,我沒有像YUI,jQuery等庫的豪華感,並且需要堅持基礎。JavaScript獲取元素類沒有任何庫

具體而言,我在一個表上循環,並希望檢查單元的類。

我想:

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

var colClass = el.class; 

但無論似乎是工作。在上面的例子中,el是從表的單元格數組中設置的,如var el = document.getElementById('myTable').rows[y].cells[y];

回答

57

也許你應該試試這個

var colClass = el.className 
2

className

Element.className

<html> 
<body id="myid" class="mystyle"> 

<script> 
var x=document.getElementsByTagName('body')[0]; 
document.write("Body CSS class: " + x.className); 
document.write("<br>"); 
document.write("An alternate way: "); 
document.write(document.getElementById('myid').className); 
</script> 

</body> 
</html> 
12

這一行,你要發佈工作:

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

你能張貼你的瀏覽器中得到什麼樣的錯誤?確保el不爲null。

如果你不會得到一個工作,the attribute of the object is className, not class

var colClass = el.className; 
+1

的getAttribute( '類')返回null上使用的className。對於相同的元素,.className返回了該類。 – Zugwalt 2010-08-10 22:27:06

+0

@Zugwalt - 自從發佈以來,這已經很長時間了。你知道爲什麼getAttribute可能會失敗嗎? – HelloWorldNoMore 2016-05-10 18:37:37

+0

@HelloWorldNoMore它可能出現在像IE6或IE7之類的舊瀏覽器中 – Zugwalt 2016-05-12 16:27:30

0

記住:

如果你得到一個錯誤, className不起作用,這可能是由於你的元素是一個jQuery對象。

works not on jquery

在你上面的圖片中看到,我canot一個jQuery對象