4

My code looks like this:

function myFunction(result) {
    var json = JSON.parse(result)
    var jsonKeys = Object.keys(json)
    var items = document.getElementById("items");
    var adds = items.getElementById("add");
    clearA()
    var i;
    for (i = 0; i < jsonKeys.length; i++) {
        var btn = document.createElement("BUTTON");
        console.log(jsonKeys[i]);
        btn.innerHTML = jsonKeys[i]
        btn.setAttribute("id", jsonKeys[i]);
        btn.onclick = function() { run(this.id); }
        items.appendChild(btn)
    }
     
    
}

I can get items and use them but when I try to get the child element "add" I get items.getElementById is not a function

This is the html:

<div id="items">
    <div id="add">
        <input type="submit" value="add" onclick="foo(add)">
    </div>
</div>
theknightD2
  • 321
  • 6
  • 17
  • hello. look it - https://stackoverflow.com/questions/16475636/why-does-getelementbyid-not-work-on-elements-inside-the-document-element/16475657 – s.kuznetsov Jan 08 '21 at 23:57
  • May I ask: why do you need `var adds = items.getElementById("add");` in the first place? You never use it in the function. In case you needed it for code that is not shown then go for `var adds = document.getElementById("add");` as @GBra pointed out. – Giampaolo Ferradini Jan 09 '21 at 00:49

2 Answers2

3

Change it to:

  var items = document.getElementById("items");
  var adds = document.getElementById("add");
GBra 4.669
  • 1,512
  • 3
  • 11
  • 23
2

Since ids are meant to be unique on a document, only document.getElementById exists. You could use items.querySelector('#id'), but this is probably a manifestation of a larger problem where you have similar HTML structure for multiple elements, with duplicated ids. In this case, it is recommended that you switch to classes and use items.querySelector('.classname').

Unmitigated
  • 76,500
  • 11
  • 62
  • 80