简体   繁体   中英

How do I get elements that were created using the DOM instead of HTML?

I tried to use document.getElementsByClassName , but when I did that it gave me a collection of elements like this:

HTMLCollection(2)
0: button#1.remove
1: button#2.remove
length: 2
2: <unreadable>
__proto__: HTMLCollection

When I tried to iterate through it there was nothing in the HTML Collection. I also tried to find the length of the HTML Collection, but it said it was 0. Also these buttons were created using JavaScript. The buttons created using HTML I am able to iterate through.

    document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('submit-note').addEventListener('click', add, false);
    document.getElementById('clear').addEventListener('click', clear, false);
    document.getElementById('copy').addEventListener('click', copy, false);
    updateNotes();
    chrome.storage.onChanged.addListener(updateNotes);
    document.addEventListener('keydown', function(event) {
        if (event.keyCode == 13) {
          add();
        }
      });
    var elements = document.getElementsByClassName('remove');
    console.log(elements);
    console.log(elements.length);
    for (item of elements) { 
        console.log(item);
      } 
})

function updateNotes() {
    document.getElementById("note-container").innerHTML = "";
    chrome.storage.local.get(['notes'], function (result) {
        var curNotes = result.notes;
        console.log(curNotes)
        if (curNotes) {
            for (var i = 0; i < curNotes.length; i++) {
                var parsedDate = new Date(JSON.parse(curNotes[i].date))
                var hour = parsedDate.getHours().toString() + ":" + parsedDate.getMinutes() + "am";
                if (parsedDate.getHours() > 12) {
                    hour = parsedDate.getHours() - 12;
                    hour = hour.toString() + ":" + parsedDate.getMinutes() + "pm";
                }
                
                var greatNote = document.createElement("div")
                var fullNote = document.createElement("div")
                var deleteContianer = document.createElement("div");

                var para = document.createElement("p");
                var node = document.createTextNode(curNotes[i].note);
                para.appendChild(node);

                var date = document.createElement("p");
                var dateNode = document.createTextNode(`${parsedDate.getMonth() + 1}/${parsedDate.getDate()}/${parsedDate.getFullYear()} - ${hour}`);
                date.appendChild(dateNode);

                fullNote.appendChild(para);
                fullNote.appendChild(date);

                var remove = document.createElement("button")
                remove.innerHTML = "D";
                remove.id = curNotes[i].id.toString();
                deleteContianer.appendChild(remove);
                
                var element = document.getElementById("note-container");
                greatNote.appendChild(fullNote);
                greatNote.appendChild(deleteContianer);
                element.appendChild(greatNote);

                para.classList.add('note-text');
                date.classList.add('date-text');
                fullNote.classList.add('full-note');
                remove.classList.add('remove');
                greatNote.classList.add('great-note')
            }
        }
    })
}

That was my first comment:

When you call updateNotes() It is calling that asynchronous function and it is its callback that creates the.remove class elements you look for. So when calling console.log(elements.length), a couple lines after... The async callback has not executed yet.

What I forgot to tell is to add new Promise() somewhere.

So you have to add await in front of updateNotes() because that is where you need to wait. But it has to be a promise, else it is considered an already resolved promise... And won't wait. See await documentation .

So here is what I would try (I skipped a couple lines for clarity):

async function functionName (){
  // ...
  await updateNotes();
  // ...
}

async function updateNotes() {
  return new Promise( resolve =>{
  
    document.getElementById("note-container").innerHTML = "";
    await chrome.storage.local.get(['notes'], function (result) {
      // ...
    }
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM