向没有ID的div添加ID

时间:2018-09-07 04:21:35

标签: javascript jquery html

嘿,我正在尝试向所有没有ID的div添加ID。

我是新来的,做了一些研究,但是找不到我需要的东西,甚至不确定是否可以做到这一点?

我确实做了一些尝试,但是即使每个div已经有一个,也只能添加一个id,但是如果没有,我只想给它一个id。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="margin: 30px -6px 0px; height: 250px;">
  <div id="advertCenterPanel" class="text-center">
    Somthing here
  </div>
</div>

<div style="margin: 30px -6px 0px; height: 250px;">
  <div id="advertCenterPanel" class="text-center">
    Somthing here
  </div>
</div>

如果有人能指出我正确的方向,我将不胜感激

4 个答案:

答案 0 :(得分:1)

您可以使用选择器div选择所有没有ID的div:not([id]),然后使用querySelectorAll遍历它们。请注意,同一文档中的重复ID是无效的HTML -您应将较低的advertCenterPanel更改为advertCenterPanel2,以使其有效(或使用类,目前尚不清楚这些ID的用途是什么。

document.querySelectorAll('div:not([id])')
  .forEach((div) => {
    div.id = 'random' + Math.random().toString(36).slice(2);
  });
console.log(document.body.innerHTML);
<div style="margin: 30px -6px 0px; height: 250px;">
  <div id="advertCenterPanel" class="text-center">
    Somthing here
  </div>
</div>

<div style="margin: 30px -6px 0px; height: 250px;">
  <div id="advertCenterPanel2" class="text-center">
    Somthing here
  </div>
</div>

答案 1 :(得分:1)

您可以尝试下面的逻辑,在其中可以过滤所有div,并确定id是否存在,如果不存在,则添加一个。

$(function(){
  var idCount=0;
  $("div").filter(function(){
     return !$(this).attr('id');
  }).attr('id', "dynamicId" + idCount++);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="margin: 30px -6px 0px; height: 250px;">
  <div id="advertCenterPanel" class="text-center">
    Somthing here
  </div>
</div>

<div style="margin: 30px -6px 0px; height: 250px;">
  <div id="advertCenterPanel" class="text-center">
    Somthing here
  </div>
</div>

答案 2 :(得分:0)

由于您使用过jquery,因此可以尝试以下操作:

$("elementSelector").uniqueId();

参考:https://api.jqueryui.com/uniqueId/

为匹配的元素集生成并应用唯一的ID。

答案 3 :(得分:0)

您可以遍历每个div并检查alredy是否具有如下所示的ID

$(document).ready(function(){
    $('div').each(function(){
        if($(this).attr('id')) {
            $(this).addClass('red');
            $(this).attr('id','mynewid');
            //do anything
        }
    })
}); 

现在在CSS中,您可以在元素获得mynewid之类的内容时添加内容

#mynewid {
    background: yellow;
}
相关问题