Jump to content

DOM: create "class" attr in one code line?


kebrus

Recommended Posts

hey everyone, i've just register to clarify this doubt that i havei hope there is no problem on posting DOM questions herei'm working on a script in which i need to create an attribute to a tag element, i can do it fine fine with the createAttribute function and setAttribute, my question here is that my attribute is the normal "class" HTML attributei thought that

elementeVarName.class = "blabla";

would work but it doesn't (i've searched everywhere in w3schools and i can find the .id the .name but not the .class)instead i have to do this

var a = document.createAttribute('class');a.nodeValue = 'blabla';elementeVarName.setAttributeNode(a);

now think of multiplying this code over and over just for the "class" attribute :) why the first doesn't exist? is there any simplier way?[edit]obviously i created a function to do it, but i still looking for an answer :)[/edit]

Link to comment
Share on other sites

Hi,You have a DOM property by name className which can be used to assign a CSS Class to a HTMl element.For e.g.: <elementVarName>.className = "blahblah";Refer to the HTMl Code Below:

<!doctype html public "-//w3c//dtd html 4.0 transitional//en"><html><head><title>Dynamic Class</title>	<meta name="Author" content="Chandra Vedantham">	<meta name="Description" content="Html Page">	<style>		*		{			font-family: "Tahoma";		}		.bigRed		{			font-size: 25px;			font-weight: bold;			color: "Red";		}		.bigBlue		{			font-size: 25px;			font-weight: bold;			color: "Blue";		}	</style></head><body>	<div id="divTest">Chandu</div>	<input type=button value="Make It Red!" onClick="divTest.className = 'bigRed'" />	<input type=button value="Make It Blue!"  onClick="divTest.className = 'bigBlue'" />	<input type=button value="Make It Normal!"  onClick="divTest.className = ''" /></body></html>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...