skip to Main Content

I have a simple JQUERY script that I have in the document head.

$(window).on('load', function() {
     $(".quick-book-pc").prepend("<p>prepended paragraph</p>")
});

It supposed to locate the first DIV with the class .quick-book-pc and add the paragraph and inner text, When the window loads there are no errors but the paragraph is not added.

If I run the script in the console it adds the paragraph fine.

What am I missing?

2

Answers


  1. Here is an example for your reference:

    $( document ).ready(function() {
         $(".quick-book-pc").prepend("<p>prepended paragraph</p>");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="quick-book-pc">
      quick-book-pc
    </div>
    Login or Signup to reply.
  2. Seems your DIV.quick-book-pc is added after the page load. Use MutationObserver to detect that:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    
    const callback = mutationList => {
      for (const mutation of mutationList) {
        const parent = $(mutation.addedNodes).filter(".quick-book-pc");
        if(parent.length){
          parent.prepend("<p>prepended paragraph</p>");
          observer.disconnect();
          observer = null;
          return;
        }
      }
    };  
    
    let observer;
    const div = $(".quick-book-pc");
    if(!div.length){
      observer = new MutationObserver(callback);
      observer.observe(document.body,  { childList: true, subtree: true });
    } else {
      $(".quick-book-pc").prepend("<p>prepended paragraph</p>");
    }
    
    setTimeout(() => $('body').append('<div class="quick-book-pc">quick-book-pc</div>'));
    
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search