从具有多个类的div中选择一个类并将其添加为id?

时间:2017-11-28 10:07:18

标签: jquery html

我正在尝试从具有多个类的div中选择一个类并将其打印为id。

当前代码:

<div class="name  usrname1  views-row">
  <div class="views-field views-field-field-user-name">
    <div class="field-content">John</div>
  </div>
</div>
<div class="name  usrname2  views-row">
  <div class="views-field views-field-field-user-name">
    <div class="field-content">Jane</div>
  </div>
</div>

在这段代码中,我需要创建“usrname1”并将其设为id。该类动态地改变并且是唯一的。

我需要什么:

<div class="name  usrname1  views-row" id="usrname1">
  <div class="views-field views-field-field-user-name">
    <div class="field-content">John</div>
  </div>
</div>
<div class="name  usrname2  views-row" id="usrname2>
  <div class="views-field views-field-field-user-name">
    <div class="field-content">Jane</div>
  </div>
</div>

https://jsfiddle.net/farhanmae/agx6t0wy/1/

2 个答案:

答案 0 :(得分:0)

这是我能找到的最佳解决方案。

遍历所有divs搜索div班级usrname。找到后,将其添加到所选id

div

&#13;
&#13;
$(document).ready(function() {
  /* Loop through all divs */
  $("div").each(function() {
    var divElem = $(this) ;
    var cls = $(this).attr("class") ; //Get the div classes
    
    /* If class has the string "usrname" */
    if (cls.indexOf("usrname") !== -1) {
      var clsArr = cls.split(" ") ; //Split the cls string into an array holding all the classes.
      
      /* Loop through the array */
      clsArr.forEach(function(clsName) {
          /* If class has the string "usrname" */
          if (clsName.indexOf("usrname") !== -1) {
            divElem.attr("id", clsName) ; //Add the class to the id of the selected div
          }
      });
    }
  }) ;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="name usrname1 views-row">
  <div class="views-field views-field-field-user-name">
    <div class="field-content">John</div>
  </div>
</div>
<div class="name usrname2 views-row">
  <div class="views-field views-field-field-user-name">
    <div class="field-content">Jane</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

jQuery Selectors使用此:$("[class*='username']")选择包含word username的所有对象。 (我认为即使它有username[number]也会选择)然后您可以使用$.each来遍历该数组并使用您希望的类更改id。您可以执行object.id = object.class.indexOf('username')之类的操作,也可以使用拆分。