如何用原生的js删除标签中的类名和添加类名?


假如一个标签中中有很多类名,我想删除其中的一个,或者给这个标签添加一个类名
该怎么做,我知道jquery很好实现,但我需要的是js,网上的感觉好复杂,还用到了正则,不知有什么简单的方法。

web前端开发 HTML css

小虫子飞啊飞 9 years, 9 months ago

function getByClass(oParent,sClass){
if(oParent.getElementsByClassName){
return oParent.getElementsByClassName(sClass);
}else{
var arr=[];
var reg=new RegExp('\b'+sClass+'\b');
var aEle=oParent.getElementsByTagName('*');
for(var i=0; i<aEle.length; i++){
if(reg.test(aEle[i].className)){
arr.push(aEle[i]);
}
}
return arr;
}
}

function hasClass(obj,sClass){
var reg=new RegExp('\b'+sClass+'\b');
return reg.test(obj.className);
}

function addClass(obj,sClass){
if(obj.className){
if(!hasClass(obj,sClass)){
obj.className+=' '+sClass;
}
}else{
obj.className=sClass;
}
}

function removeClass(obj,sClass){
var reg=new RegExp('\b'+sClass+'\b','g');
if(hasClass(obj,sClass)){
obj.className=obj.className.replace(reg,'').replace(/^\s+|\s+$/g,'').replace(/\s+/g,' ');
}
}

琪露诺⑨. answered 9 years, 9 months ago

看了上面的答案,虽然有的空格不影响浏览器渲染结果,但强迫症患者觉得还是用正则靠谱。原来元素不包含类名的话添加的时候就不需要空格。如果已有元素,添加的时候就加空格,删除的时候,需要删除类名首空格。还是删除类名尾的空格。使用正则可以对付处理这些空格的情况。

尘零零零零 answered 9 years, 9 months ago

我修改了一下1L的答案,注意空格

var classVal = document.getElementById("id").getAttribute("class");

classVal = " " + classVal + " ";

//删除的话,有三个地方加空格
classVal = classVal .replace(" someClassName "," ");
document.getElementById("id").setAttribute("class",classVal );

//添加的话,有一个地方加空格
classVal = classVal .concat(" someClassName");
document.getElementById("id").setAttribute("class",classVal );

//替换的话,有四个地方加空格
classVal = classVal .replace(" someClassName "," otherClassName ");
document.getElementById("id").setAttribute("class",classVal );

金麟岂是池中物 answered 9 years, 9 months ago

试试这个


 var classVal = document.getElementById("id").getAttribute("class");

//删除的话
classVal = classVal.replace("someClassName","");
document.getElementById("id").setAttribute("class",classVal );

//添加的话
classVal = classVal.concat(" someClassName");
document.getElementById("id").setAttribute("class",classVal );

//替换的话
classVal = classVal.replace("someClassName","otherClassName");
document.getElementById("id").setAttribute("class",classVal );

只是匹配个class名字,用不着正则应该。

Plucima answered 9 years, 9 months ago

可以参考一下 classList ,提供了 add remove toggle 以及 contains 等方法方便操作 className
http://www.zhangxinxu.com/wordpress/2013/07/domtokenlist-html5-dom-cla...

xchuner answered 9 years, 9 months ago

Your Answer