Search code examples
javascriptmenu

Getting All Same IDs with Javascript


The javascript only get the first id. The 2nd id ignores the code. Are there anyway to make both IDs using the same javascript ?

<div class="tab">
  <button class="tablinks" onclick="openProgram(event, 'add_item')" id="defaultOpen">Add Item</button>
  <button class="tablinks" onclick="openProgram(event, 'list_item')">List Items</button>
</div>

<div id="add_item" class="tabcontent">
<div id="subcatchooser"></div>   

<div id="list_item" class="tabcontent">

<div id="subcatchooser"></div>

Javascript here

function showsubcat(str) {
  if (str.length == 0) { 
    document.getElementById("subcatchooser").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("subcatchooser").innerHTML = this.responseText;
      }
    };
    xmlhttp.open("GET", "ajax.php?action=showsubcat&parent_id=" + str, true);
    xmlhttp.send();
  }
}

Solution

  • That is the main difference between classes and IDs. Classes are designed to be used multiple times, while IDs are designed to be unique. So you can change the divs to look like this:

    <div class="subcatchooser"></div>
    

    And then change the JavaScript to look like this:

    var elements = document.getElementsByClassName("subcatchooser");
    for (var i = 0; i < elements.length; i++) {
      elements[i].innerHTML = "";
    }