-2

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>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Abhi
  • 67
  • 7

3 Answers3

1

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

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);
}
Colorado Akpan
  • 306
  • 1
  • 12
0

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>

gaurav
  • 491
  • 3
  • 13
  • That does not *guarantee* uniqueness of "id" values. – Pointy Nov 13 '21 at 13:05
  • It's your choice, if you want to use uuid4. – gaurav Nov 13 '21 at 13:07
  • The point is that the `.uniqueId()` function the OP tried to use (incorrectly) **does** guarantee a unique id value for every affected element. – Pointy Nov 13 '21 at 13:10
  • Please do not give additional information on your question in an answer. Instead, edit your question. I already did that for you in this case, so please delete this answer. – connexo Nov 13 '21 at 13:11