以下代码不是最简洁的,但对于学习者来说更容易理解。
JS如何获取指定DIV下的子元素LI值
var div=document.getElementById('a');
var ul=div.childNodes.item(0);
var lis=ul.childNodes;
for(var i=0;i<lis.length;i++){
alert("Item "+i+": "+lis.item(i).innerHTML);
}
JS怎么获取当前点击的子元素的下标
var
child = document.getElementsByClassName(
"child"
);
for
(
var
i = 0; i < child.length; i++) {
var
a = child[i];
a.index = i;
//给每个className为child的元素添加index属性;
a.onclick =
function
() {
alert(
this
.index)
}
}
原生JS实现addClass
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 );
Object.prototype.hasClass = function(cls) {
return this.className.match(new RegExp('(\s|^)' + cls + '(\s|$)'));
};
Object.prototype.addClass = function(cls) {
if (!this.hasClass(cls)) this.className += " " + cls;
};
Object.prototype.removeClass = function(cls) {
if (this.hasClass(cls)) {
var reg = new RegExp('(\s|^)' + cls + '(\s|$)');
this.className = this.className.replace(reg, ' ');
}
};
Object.prototype.toggleClass = function(cls){
if(this.hasClass(cls)){
this.removeClass(cls);
}else{
this.addClass(cls);
}
};
.aaa {
background: red;
}
<div id="choumafen1" class="hsds">test div</div>
function addClass(element,value){
//如果元素类名为空,直接将value赋值给相应的元素类名
console.log(element.className)
if(!element.className){
element.className = value;
}else{
//否则需要将类名之间用空格隔开
newClassName = element.className;
//多个类名间添加空格
newClassName += ' ';
newClassName += value;
element.className = newClassName;
}
}
var choumafen1=document.getElementById("choumafen1")
addClass(choumafen1,'aaa')
作者:
https://zhidao.baidu.com/question/211012353.html
https://zhidao.baidu.com/question/982131582421985059.html
http://www.javascriptcn.com/read-1011.html
如何用原生的js删除标签中的类名和添加类名?
https://segmentfault.com/q/1010000002955089?sort=created
原生js添加删除class
http://blog.csdn.net/magicw3/article/details/45537725