'Element not really recognized
I got a website which I am currently building modals (these popping up windows) into but I got a problem with Javascript.
The big problem here is that the elements, added by a Javascript code executed before are there but not really recognized.
So if I execute this
var i,s;
for(var i=0;i<(s = document.getElementsByClassName('param-descr')).length;i++) s[i].addEventListener('click', (e) => {
openModal('Beschreibung von '+e.currentTarget.innerText, e.currentTarget.getAttribute('aria-label'), 'modal-param-descr');
});
console.log(s);
console.log(s.length);
it prints firstly an array of 6 length into the console and then 0.
HTML of the scripts looks like this
<script src="content.js"></script><script src="funcs.js"></script>
and the Content is being added by fetching a JSON File, converting it all to HTML Elements and adding them to the website. (It shall be an Online Discord Bot Help)
What I have tried so far
I tried the DOMContentLoaded Event, the load event (both on document) and defining s separately, all failing.
The only solution that worked yet was to add a setTimeout of 1sec which could not succeed as the loading speed on each computer is different. With this I tested it all and thus I can say it would work with a proper Trigger.
Solution 1:[1]
Sorry, mistake on my part.
Got a thought this morning how fetch() works and that it could be asynchronous which it is.
This causes the program to not really have registered the elements but they are existing as the other function is running beside this.
Solution: Changing fetch() and .then to
var request = new XMLHttpRequest();
request.open('GET', 'JSON_FILE', false);
request.send(null);
if (request.status === 200) {
add_content(JSON.parse(request.responseText));
}
Maybe should've made that thing with fetching clearer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FlexGames |
