Home > front end >  How to get dynamically inserted elements in JS (Like ADBLOCK)?
How to get dynamically inserted elements in JS (Like ADBLOCK)?

Time:07-11

I'm inserting some dynamically tags every 1 second after page load, how could I get these elements with js. The logic would be similar to an ADBLOCK? for example

var anyTag = document.createElement('span');

setInterval(function() {
   document.body.append(anyTag);
}, 1000);

// getting the tags dynamically inserted
setInterval(function() {
//here I wanted to be able to get these elements that were added
// span, span, span...
}, 100);

CodePudding user response:

One option is to select all such elements on the page initially, then do the same later and compare the differences.

const liveSpans = document.getElementsByTagName('span'); // live collection
let oldSpans = [...liveSpans];
setInterval(() => {
  const spansNow = [...liveSpans];
  for (const span of spansNow) {
    if (!oldSpans.includes(span)) {
      // this span was inserted
    }
  }
  oldSpans = spansNow;
}, 1000);

Note that if you do

setInterval(function() {
   document.body.append(anyTag);
}, 1000);

you're inserting the same element each iteration - if you want to insert a new element each time, create it inside the interval callback.

If you want to get the spans that were inserted immediately upon insertion, attach a MutationObserver to a parent element (in this case, the document.body) with { childList: true } and a callback can be attached which runs whenever elements are inserted (or removed). (Look through the .addedNodes)

CodePudding user response:

Since you're creating the elements you should have a reference to them at the time of creation. Thus, the simplest solution is to store the elements you're creating in a variable, like putting them in an Array:

const createdElements = [];

setInterval(function() {
   const element = document.createElement('span');
   document.body.append(element);
   createdElements.push(element);
}, 2000);

setInterval(function() {
   // getting the tags dynamically inserted
   createdElements.forEach(element => {
     console.log('I created', element);
   });
}, 1000);

Alternatively, just make sure the elements are findable by giving them something like a distinctive className so you can find them later.

setInterval(function() {
   const element = document.createElement('span');
   element.setAttribute('className', 'find-me-later');
   document.body.append(element);
}, 2000);

setInterval(function() {
   // getting the tags dynamically inserted
   document.querySelectorAll('.find-me-later');
}, 1000);
  • Related