多个相同span标签给特定的标签添加class

原创 米斯达科 随笔 javascript 152阅读 2018-06-28 13:59:46 举报

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.red{
color:red;
}
.org{
color: blue;
}
</style>
</head>
<body>
<div id="demo">
<span>测试112323</span> <!-- 加载过后 带 red -->
<a>343434</a>
<span>1</span> <!-- 加载过后 带 org -->
<span>444</span> <!-- 加载过后 带 red -->
</div>
</body>
<script type="text/javascript">
window.onload = function(){
var form = document.getElementById('demo').getElementsByTagName('span')
console.log(form,'123')
//form.innerHTML = '123';
//form.className ="red";
//form.setAttribute('className','red')

    /*方法1*/
    for (var i = 0; i < form.length; i++) { //给所有的span的标签添加class
         //form[i].className ='red' ;
        //if(i = '1' )  //进入死循环
        if(i == 1 ){
            form[1].className ='org' ;
        }else{
            form[i].className ='red' ;
        }

    }

    /*方法2*/
    var form = document.querySelectorAll('span')

    Array.prototype.forEach.call(form, function(item, index){
    //[].forEach.call(form, function(item, index){  
        item.className = index  == 0 ? 'red':'org'

    })

}

</script>
</html>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复