为div添加唯一的类

时间:2017-05-29 09:14:11

标签: javascript jquery css

我想为每个div添加一个新类但是唯一的,我如何使用jQuery创建它?

<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>

CodePen Project

5 个答案:

答案 0 :(得分:1)

快速,纯粹的js方法:

&#13;
&#13;
// for adding unique classes:
// var divs = document.querySelectorAll('.pat');
// [].forEach.call(divs,(el,i)=>{
//   el.classList.add('myclass_'+i)
// })

//for adding unique id's
var divs = document.querySelectorAll('.pat');
[].forEach.call(divs,(el,i)=>{
  el.id = 'myId_'+i;
})
&#13;
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试使用jquery的each()attr()函数。请尝试使用id代替class获取唯一

适用于unique id

$('.pat').each(function(a,b,c){
 $(this).attr('id',$(this).attr('class')+a)
})
console.log($('body').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pat"></div>
<div class="pat"></div>
<div class="pat"></div>

答案 2 :(得分:0)

将所有div包含在包装器中。

 <div id="wrapper">
      <div class="pat"></div>
      <div class="pat"></div>
      <div class="pat"></div>
    </div>

<script type="text/javascript">
$( document ).ready(function() {
  $("#wrapper div").each(function(key){
     $(this).addClass("newclass"+ key);
  });
});

</script>

答案 3 :(得分:0)

您可以使用此代码

var divElements = document.getElementsByTagName('div');
console.log(divElements.length);
var c=0;
Array.prototype.forEach.call(divElements,function(a) {
    a.classList = "div-" +c;
    c++;
    console.log(a);
})

答案 4 :(得分:0)

试试这个:

&#13;
&#13;
$(document).ready(function(){

        $("div").each(function(index) {
        
            $(this).addClass('pat'+index)
            
    });
});
&#13;
.pat0 {
 	background-color: red;
}

.pat1 {
       background-color: blue;
}

.pat2 {

      background-color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="pat">Pat0</div>
<div class="pat">Pat1</div>
<div class="pat">Pat2</div>
&#13;
&#13;
&#13;