1

I'm trying to get the value of an element. but I'm facing a problem.

when the dom content is loaded after some time that element gets added.

and If I try to select it I get null. I have tried window.addEventListener('DOMContentLoaded', doSomething) but It didn't helped me.

I have done something similar with an img element by adding the load event listener. but I can't add the load event listener here because it's null.

document.querySelector('.some-element')

How can I do this?

Xaarth
  • 1,021
  • 3
  • 12
  • 34
  • You can use MutationObserver, https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver, you don't need to add timeout function – lissettdm Dec 05 '20 at 23:10

2 Answers2

2

I recommend you MutationObserver to watch for changes being made to the DOM tree. Once the element is part of the DOM you can call disconnect() function.

const targetNode = document.querySelector("body");

const observer = new MutationObserver((mutationList, observer)=> {
  mutationList.forEach( (mutation) => {
   if(mutation.type === 'childList') {
     console.log(mutation.addedNodes);
   }
  })

});
observer.observe(targetNode, {
  childList: true,
});

setTimeout(() => {
  const someElement = document.createElement("div");
  someElement.className = "some-element";
  someElement.textContent = "Some Element";
  document.body.appendChild(someElement);
}, 1000);
lissettdm
  • 12,267
  • 1
  • 18
  • 39
-1

Solution WITHOUT setTimeout as we no idea what exact time after which the element will be loaded.

document.addEventListener('DOMNodeInserted', function(event){
      // Do something here
      console.log("new element added in DOM")
}, true);



setTimeout(function() {      
  var d1 = document.getElementById('one');
      d1.insertAdjacentHTML('beforeend', '<div id="two">two<input type="text" value="Hello" class="some-element"/></div>');
}, 2000);
<div id="one">One</div>
GMKHussain
  • 3,342
  • 1
  • 21
  • 19