Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all selectors by class name that were dynamically appended in vanilla JavaScript?

Tags:

javascript

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.

like image 395
Matt Komarnicki Avatar asked Oct 22 '15 11:10

Matt Komarnicki


1 Answers

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

like image 101
hsz Avatar answered Oct 30 '22 16:10

hsz