0

I am having issue removing dynamically added attributes from HTML. There is a parent component(not controlled by me) which has a click functionality where it calls an API and adds a HTML element to the DOM. Now i have to remove this element from DOM when the click functionality is done and HTML is rendered. I tried below two methods, but did not had luck as the element is unavailable

window.addEventListener('load', function(){
  const ele = document.getElementById("remEle");
  console.log(ele)

})

$(document).ready( function() {
      const ele = document.getElementById("remEle");
      console.log(ele)

})


<div id="container">
  <div class="header-class" id="remEle">
    "Header"
     <div class="item-class">item</div>
  </div>
</div>

In both the cases i am getting "ele" as undefined and not able to remove it.

Deadpool_er
  • 215
  • 4
  • 20
  • 2
    What does the html look like? Also, you have a typo: `addEventListner` should be `addEventListener`. – mykaf Aug 15 '23 at 20:27
  • 2
    If the element loads on the click event, then the load event would not be appropriate for removing it; the element doesn't exist yet when loading. Perhaps you can add another listener to the click event to remove it. – mykaf Aug 15 '23 at 20:29
  • updated HTML and corrected the typo. As i mentioned the code for click event is not in my control, Is there any way i can alter this on my side with element information? – Deadpool_er Aug 15 '23 at 20:33
  • Do these elements get dynamically loaded? Or are they present in the HTML file? – Josh Aug 15 '23 at 20:33
  • @Josh they are dynamically loaded on click there is an ajax call and receiving response the elements will be added. – Deadpool_er Aug 15 '23 at 20:34
  • You should be able to add another listener to the click event that loads the element. *Maybe* use `setTimeout()` to give the ajax time to do its thing. – mykaf Aug 15 '23 at 20:34
  • 1
    Well, there's your problem. You need to wait for the element to exist. I use this script when I have that need: https://bobbyhadz.com/blog/javascript-wait-for-element-to-exist – Josh Aug 15 '23 at 20:35
  • You can use a `MutationObserver` to execute code when the element is created. – Barmar Aug 15 '23 at 20:41

0 Answers0