I need to get / count how many elements with a common class target
name are "available". None on those elements physically exists in the DOM. Those items have been added later when the page was fully loaded.
Below
var targets = document.getElementsByClassName('target');
when I console.log(targets);
I get []
.
When I click those square brackets, they expand and target
items seems to appear but next to them there's a message:
Object value at left was snapshotted when logged, value below was evaluated just now.
So I assume that I did console.log
when DOM hasn't been populated with target
elements yet. How do I get information about dynamically added elements?
EDIT:
I checked hsh's functions and
document.body.addEventListener('DOMSubtreeModified', function(event) {
var targets = document.getElementsByClassName('target');
console.log(targets.length);
/**
* If I have 40 target elements, this will be called 40 times :/ showing first bunch of zeros then finally number will reach to 40
*/
});
/**
* So this would be ideally (called only once) but this always shows empty array and 0
*/
document.addEventListener('DOMContentLoaded', function(event) {
var targets = document.getElementsByClassName('marker');
console.log(targets); // always shows []
console.log(targets.length); // always shows 0
//while I can play with those target selectors in Chrome Dev Tools
});
PS. No jQuery please.
You can call your check script in DOMContentLoaded
event:
document.addEventListener('DOMContentLoaded', function(event) {
var targets = document.getElementsByClassName('target');
console.log(targets);
});
Also you can use DOMSubtreeModified
event if you're expecting that something will be added during the runtime.
document.body.addEventListener('DOMSubtreeModified', function(event) {
var targets = document.getElementsByClassName('target');
console.log(targets);
});
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With