Set unique ID for multiple HTML elements

by Akram kamal

HTML

<h1>Set unique ID for multiple HTML elements</h1>

<hr/>

<h2>Cointainer #1</h2>

<em>With no ID set to all the span's inside the Cointainer.</em>

<br/>
<div id="parent1" class="parent"> 
    <span>11</span>
    <span>12</span>
    <span>13</span>
    <span>14</span>
    <span>15</span>
    <span>16</span>
</div>
<br/>

<h2>Cointainer #2</h2>

<em>With unique ID set for all the span's using jQuery.</em>

<br/>
<div id="parent2" class="parent"> 
    <span>11</span>
    <span>12</span>
    <span>13</span>
    <span>14</span>
    <span>15</span>
    <span>16</span>
</div>

CSS

body {
    font-family:"Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
    font-size: 70%;
}
.parent {
    padding:8px;
    margin:8px;
    border:2px solid #333;
    -moz-border-radius: 8px;
    -webkit-border-radius: 8px;
    border-radius: 8px;
    -khtml-border-radius: 8px;
}
span {
    padding:5px 10px;
    margin:5px 10px;
    border:2px solid green;
    display:inline-block;
}
span[id^="span"] {
    padding:5px 10px;
    margin:5px 10px;
    border:2px solid blue !important;
    display:inline-block;
}

JavaScript

// Get all the span's inside parent2
var $span = $("#parent2 span");

// Set the id for span's based on the position in the page.
$span.attr('id', function (index) {
    return 'span' + index;
});