Example of Why IDs Need to be Unique

by Alexander

HTML

<p>
  This is an example scenario demonstrating why it's important for the every element ID to be unique on a page.
</p>
<p>
  This example is intended to mimic a scenario where two instances of the same DNN module have been added to a page.
</p>
<p>
  Each instance of the module is wrapped in a <code>div</code> element with the <code>it-project-request-form</code> CSS class applied, which contains two <code>input</code> elements. The first input element has a hard-coded ID, whereas the second <code>input</code>  element is only referenced using a class.
</p>
<p>
  <b>Note:</b> Although we are refering CSS classes on our elements, we aren't defining any actual CSS classes in our stylesheet. This is acceptable, as we're only using the CSS classes in our jQuery selectors for the elements that can appear multiple
  times on a page.
</p>

<h2>Module Instance #1</h2>
<div class="it-project-request-form">
  <label>Input with ID</label>
  <input id="txtEmail" type="text">
  <br>
  <label>Input with class</label>
  <input class="email-lookup" type="text">
</div>
<hr/>
<h2>Module Instance #2</h2>
<div class="it-project-request-form">
  <label>Input with ID</label>
  <input id="txtEmail" type="text">
  <br>
  <label>Input with class</label>
  <input class="email-lookup" type="text">
</div>
<hr/>
<p>
  In teh JavaScript pane, we have two lines of code that just set the background color of the elements. Notice how the input with ID in the second module instance isn't styled, but both inputs with the class are styled as we would expect.
</p>
<p>
  Here are several relevant links with additional information:
</p>
<ul>
  <li>
    <a href="https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really">
        SoftwareEngineering.StackExchange.com &ndash; Two HTML elements with same id attribute: How bad is it really?
      </a>
  </li>
  <li>
    <a...

JavaScript

$("#txtEmail").css('background', 'yellow');

$(".it-project-request-form input.email-lookup").css('background', 'magenta');