I have a simple table, in that table, each row is added (using innerHTML) with data from local storage. Each row contains an edit button. When I querySelectAll edit buttons with the class name it returns null that doesn't make sense.
Here, Total_Users is the stored array of objects, each object pass to the addToUserList() that apply innerHTML that contains a button. With the document loaded, data is presented but querySelectorAll returns null in search of "editButt". As data is presented in DOM, several buttons should be a result which I didn't get...
// DOM
class Show {
static addToUserList(user) {
let list = document.querySelector('#table-body'); //just a table
let row = document.createElement('tr');
row.innerHTML = `<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.phone}</td>
<td>${user.role}</td>
<td class="text-center mx-auto"> <i class="fa fa-edit text-success btn editButt" data-bs-toggle="modal" data-bs-target="#edit"></i> </td>`;
list.appendChild(row);
}
}
//Fill with previously stored data
document.addEventListener('DOMContentLoaded', Load_Users);
function Load_Users() {
let Total_Users;
if (localStorage.getItem('Total_Users') === null) {
Total_Users = [];
} else {
Total_Users = JSON.parse(localStorage.getItem('Total_Users'));
}
Total_Users.forEach(item => {
Show.addToUserList(item);
})
}
// querySelector editButt
// find nothing here
let editElem = document.querySelectorAll('.editButt');
console.log(editElem);
CodePudding user response:
You need to check if the event "DOMContentLoaded" is ready, for example:
if (document.readyState === "complete" || document.readyState === "loaded") {
// document is already ready to go
// your query selector here:
let editElem = document.querySelectorAll('.editButt');
console.log(editElem);
}
check the answer to this question in detail here:
How to detect if DOMContentLoaded was fired
CodePudding user response:
You could try first selecting the "#table-body", and then use the querySelectorAll() to search through the table element. Try something along these lines:
let container = document.querySelector('#table-body');
let editElem = document.querySelectorAll('.editButt');
If that doesn't work, try using the old-fashioned getElementsByClassName selector, I've had this problem with the querySelectorAll() before and I ended up using something like this:
var editElem = document.getElementsByClassName('editButt');
If none of that works for you, I suggest adding an id to whichever element you're trying to select. That way you know for a fact you're selecting that specific element.
document.querySelectorAll() | MDN Web Docs
document.getElementsByClassName() | MDN Web Docs
CodePudding user response:
Inside the load_Users() function the querySelector works fine Here:
function Load_Users(){
....
editElements();
deleteElements();
}
function editElements(){
let editElem = document.querySelectorAll('.editButt');
console.log(editElem.length);
...
}