-2

Possible Duplicate:
How do I add a class to a given element?

I'd like to have JavaScript add a class to my h1 elements automatically.

How would I add JavaScript to replace the h1 element with h1="classs" etc?

Community
  • 1
  • 1
user1106295
  • 95
  • 2
  • 9
  • been asked my times before. check [add class to element][1] [1]: http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript – au_stan Jan 24 '12 at 15:44

5 Answers5

3

First of all, get the element by ID or by TagName. And at second, use .className = "your-class".

Wouter J
  • 41,455
  • 15
  • 107
  • 112
1

Try this:

var h1 = document.getElementsByTagName("h1");

for (i = 0; i < h1.length; i++) {
    h1[i].className += ' classs';
}

Tested on jsFiddle

Ben Everard
  • 13,652
  • 14
  • 67
  • 96
0
element.setAttribute("class", classname)

Where classname is the name of the class you want to add and element is your h1 tag.

Jivings
  • 22,834
  • 6
  • 60
  • 101
0

Using Jquery it's simple. Loop all of the h1 elements adding the classname to it

$(function(){
  $('h1').each(function(){
    $(this).addClass('classname');
  });
});

Or if you want to add a class per specific element ID

  $(function(){
    $('#eleID').addClass('classname');
  });
Pastor Bones
  • 7,183
  • 3
  • 36
  • 56
0
<h1 id='needsName'>My header</h1>

Javascript code here

document.getElementById("needsName").className = 'the_name_you_want';
Chibuzo
  • 6,112
  • 3
  • 29
  • 51