Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to an element

Tags:

javascript

I try to write these code to make grid view through CSS:( jsbin )

var tables = document.getElementsByClassName('tableData');
var rows = tables[0].getElementsByTagName('tr');
for(var i = 1; i < rows.length; i += 2) {
  alert(rows[i]);
  rows[i].className = "alt";
}

This only works with the tr elements has class="". But if I want to add class to tr.

I've tried Core.addClass but it doesn't work.

like image 858
Dzung Nguyen Avatar asked Mar 02 '10 02:03

Dzung Nguyen


1 Answers

Two years later (2012/06), there is a new and shiny approach - element.classList with methods add(), remove(), toggle(), contains().

rows[i].classList.add("alt");

Supported by

  • Chrome 8+
  • Firefox 3.6+
  • Internet Explorer 10+
  • Opera 11.50+
  • Safari 5.1+
like image 90
Petr Janeček Avatar answered Oct 14 '22 04:10

Petr Janeček