Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery create a unique id

$(document).ready(function() {
  $('a.menuitem').click(function() {
      var arr = 0;
      var link = $( this ), url = link.attr( "href" );
      var newDiv = $( document.createElement( 'div' ) )
      $( "#content_pane" ).append( newDiv );
      newDiv.load( url );
      return false;
  });
});

As you can see I am creating a div and adding some content to it, how would I give each div that is created a unique id, something like section1, section2, section3, etc?

like image 549
Udders Avatar asked Nov 29 '09 23:11

Udders


People also ask

How do I get a unique ID?

The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.

How do I set the ID of an element in jQuery?

To change the id attribute of an HTML element, you can use the jQuery attr() method which allows you to set an element's attribute value.

How to create a random id in JavaScript?

Javascript does not have any inbuilt method to generate unique ids, but it does a have method called Math. random() which generates a unique number every time called. We can use this to generate unique random ids.

What is unique ID in JavaScript?

Introduction to JavaScript UUID. A universally unique identifier (UUID) is an identifier of the 128-bit value that is used in the construction of software. Each bit present in the value differs by the meaning as several variants are considered.


1 Answers

Just use a counter:

var section = 1;
$(function() {
  $("a.menuitem").click(function() {
    ...
    $("<div></div>").attr("id", "section" + section++).appendTo("#content_pane");
    ...
    return false;
  });
});

Also, I'd suggest creating the element as per above.

like image 164
cletus Avatar answered Sep 30 '22 20:09

cletus