-1

I load an external JS that create a form and i want to change the placeholder of one of the input. I try to write the function just after the div which contains the form and target the input by the name or the class. Maybe it's just the loaded script which prevent change of the placeholder ...

document.getElementsByClassName('squeezer-widget-input-code').placeholder = 'Enter your Code';
<script type="text/javascript" src="https://dl.squeezer.fr/widget"></script>
<div class="squeezer-widget"></div>
Sam
  • 3
  • 1
  • This is a duplicate of https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method – Quentin Sep 05 '17 at 12:29
  • if form allready created when you try to change placeholder? maybe you try to change it before widget is loaded. – Davor Mlinaric Sep 05 '17 at 12:30
  • @Quentin, Form is created using externally, However you point is valid – Satpal Sep 05 '17 at 12:32
  • @Satpal — That shouldn't matter. It is still a part of the DOM. (Well, unless it is in a frame, which which case it is in a different, inaccessible DOM). – Quentin Sep 05 '17 at 12:33
  • @Quentin Thanks but i can't change the selector by an ID since it's an external file, and the input is unique in the page so i guess i could target it by its class which is unique too. – Sam Sep 05 '17 at 13:36
  • @SamuelBart — At no point did I suggest using an id instead. – Quentin Sep 05 '17 at 13:50
  • @Quentin sorry misunderstanding, i thought it was the point of your link – Sam Sep 05 '17 at 14:48

1 Answers1

0

You can use MutationObserver and listen for DOM changes for creation for <FORM>

var MutationObserver = window.MutationObserver;
var list = document.querySelector('.squeezer-widget');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type === 'childList') {
      var elem = document.querySelector('.squeezer-widget-input');
      if (elem != null)
        document.querySelector('.squeezer-widget-input').placeholder = 'Enter your Code';     
    }
  });
});

observer.observe(list, {
  attributes: true,
  childList: true,
  characterData: true
});
<script type="text/javascript" src="https://dl.squeezer.fr/widget"></script>
<div class="squeezer-widget"></div>

Note: There is no element with squeezer-widget-input-code selector, Hence used squeezer-widget-input

Do read What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?

Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Thanks a lot @Satpal, its works with `MutationObserve` and i just observe mutation of attributes and change the placeholder of squeezer-widget-input-code (which is the first input) – Sam Sep 05 '17 at 13:48