Home > Software design >  how to add id attribute and unique id inside html div tag
how to add id attribute and unique id inside html div tag

Time:11-13

I want to add id attribute and also unique id in the id attr. i tried but getting objects inside the id attribute

$("div .abc").each(function() {
  $('.abc').attr('id', $(this).uniqueId());
})
[id]::before {
  content: attr(id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
<div class="xyz">
  <div class="abc"></div>
  <div class="abc"></div>
  <div class="abc"></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The jQueryUI .uniqueId() method does all the work you need internally. It returns a jQuery object, which is why you see what looks like an object. All you need in the .each() callback is

  $(this).uniqueId();

In fact you don't even need the .each():

  $("div .abc").uniqueId();

will iterate through the matched elements and give each one a unique id value.

CodePudding user response:

Full code is here

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  </head>
  <body>
    <div class="xyz">
      <div class="abc"></div>
      <div class="abc"></div>
      <div class="abc"></div>
    </div>
  </body>
  <script>
    $(".abc").each(function (index) {
      $(this).attr("id", "abc"   index);
    });
  </script>
</html>

CodePudding user response:

yu can auto increment an id to an html element using either each loop or for loop

each loop like this;

$(".abc").each(function(i) {
  $(".abc").attr('id', 'id'   i);
})

or using for loop

for(var i = 0, i = $(".abc").length, i  ){
  $(".abc").attr('id', 'id'   i);
}
  • Related