mppowe
mppowe

Reputation: 215

Javascript to modify text in dynamically loaded element

I have a webpage that is hosted in the cloud (so I don't have access to the source code), but I'm allowed to "inject" JS at the bottom of the page. There is a button that, when pressed, will do the following:

  1. Use ajax to retrieve data
  2. Create a new HTML with the contents retrieved
  3. Uses jQuery to fadeOut the original button and fadeIn the new contents

I need to modify text in the new that gets created. The button looks like:

<button class="subform add" onclick="addSubform(stuff); return false;" ...></button>

The div that is created looks like:

<div class=" section subform container" id="myId" style=""><div class="subformheader"><h4>Text I want to modify</h4>

Since I can't access the source code, I can't change the fadeIn to include a callback to modify the text.

I tried to tie into the events for the button's click using addEventListener():

let buttonNodes = document.getElementsByClassName('section subform container')
buttonNodes[0].addEventListener('change', function(){alert("clicked me!")});

But b/c the "addsubForm()" function is ajax, my function gets executed before the ajax call gets the results and creates the new .

Any ideas?

Upvotes: 0

Views: 915

Answers (1)

zfrisch
zfrisch

Reputation: 8660

You can use a mutation observer. (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)

The problem with Mutation observers is that they're very finicky to setup. For instance, even though it's the same exact code, the code below works better in this fiddle : http://jsfiddle.net/b9sdLzrv/15/ - though I suspect that might be due to the environment.

Basically what you want to do is to test when an elements node has changed using a mutation observer. The observer allows for a callback, and then provides a method (observe) to attach it to a target element with allowed options.

That all being said, your situation is precarious. It would be best to reach out to whomever can edit the code and have them do it, or to simply find an alternative method. Not being able to touch code and/or altering it from a script after DOM load despite the initial setup is in very poor taste as it can lead to many issues in the future.

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 2000, 'Original Change Text');
}).then(msg => {
  document.querySelector("#myId").innerHTML = `<h4>${msg}</h4>`;
});



let observer = new MutationObserver(function(mutation) {
  document.querySelector("#myId").innerHTML = `<h4>immediately change the text on change`;
observer.disconnect();
});
observer.observe(document.querySelector("#myId"), {
  childList: true
});
<div id="container">
  <div class=" section subform container" id="myId" style="">
    <div class="subformheader">
      <h4>Text I want to modify</h4>
    </div>

Upvotes: 2

Related Questions