JavaScript Add, delete, change CSS style name implementation method

Source: Internet
Author: User

The code is as follows Copy Code

<script type= "Text/javascript" >


Description: Add, remove, detect ClassName

Finishing: codebit.cn (http://www.111cn.net)

function hasclass (element, ClassName) {

var reg = new RegExp (' (\s|^) ' +classname+ ' (\s|$) ');

Return Element.className.match (REG);

}

function addclass (element, ClassName) {

if (!this.hasclass (element, ClassName))

{

Element.classname + = "" +classname;

}

}


function removeclass (element, ClassName) {

if (Hasclass (element, className)) {

var reg = new RegExp (' (\s|^) ' +classname+ ' (\s|$) ');

Element.classname = Element.className.replace (Reg, ');

}

}

</script>

Instance

The code is as follows Copy Code

<style>
. unnamed1 {
Background-image:url (.. /images/botton.gif);
Background-repeat:no-repeat;
Background-position:center Center;
font-size:14px;
line-height:130%;
Text-decoration:none;
Color: #003399;
Text-align:center;
Display:list-item;
Font-weight:bold;


}
. unnamed2 {
Background-attachment:scroll;
Background-image:url (.. /images/botton1.gif);
Background-repeat:no-repeat;
Background-position:center Center;
font-size:14px;
line-height:130%;
Color: #FF0000;
Text-decoration:none;
Font-weight:bold;
Text-transform:capitalize;
Font-style:italic;
}
</style>
<script>
function Changeclass (obj)
{
var Tb=document.getelementbyid ("TB");
var tdn=tb.getelementsbytagname ("TD");
for (var i=0;i <tdn.length;i++) {
Tdn[i].classname= ' Unnamed2 ';
}
Obj.classname= ' unnamed1 ';
}
</script>
<table id=tb>
<tr> <td class=unnamed2 onclick= "Changeclass (This)" > detail 1 </td> </tr>
<tr> <td class=unnamed2 onclick= "Changeclass (This)" > detail 2 </td> </tr>
</table>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.