1

I am having an issue when trying to run JavaScript inside an Ajax loaded content on a webpage. I keep getting an error "Cannot set properties of null". If I move the output of the script to the footer for example which is outside of the Ajax loaded content, the script works fine.

This is the piece of code where the ajax is loaded into on the main webpage:

<main>
    <article class="ext-content">

    </article>
    </main>

This is the JavaScript code to load the ajax content:

$('section li').click(function() {
    $.ajax({
      type: 'GET',
      url: 'includes/ext-content/'+$(this).data('content')+'.html',
      dataType: 'html',
      success: function(response) {
        $('.ext-content').html(response);
      }
    });
  });

This is part of the ajax loaded content where when a user selects the amount of items, they are shown the price of the item * the amount selected. The shopOutput is where the price will be shown on the webpage: (If I move the shopOutput outside of the Ajax content the script works fine.)

          <tr>
            <td colspan="3" class="shop-qty-select">
                <select onchange="addElements(this)">
                  <option value="0">Select aantal:</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                </select>
                <p id="shopOutput"></p>
            </td>
        </tr>

This is the JavaScript which takes the amount selected and shows the user how much the total price will be:

let shopOutput = document.getElementById("shopOutput");

const priceFractal = 10;

function addElements(selectElement) {

  let valueNumbers = selectElement.value;

  shopOutput.innerHTML = ""; 

    let yourTotal = valueNumbers * priceFractal;
    shopOutput.textContent = yourTotal;
}

Any help is much appreciated.

Like I mentioned I know that this code works if I just move the output outside of the Ajax loaded content. But when it is inside the Ajax content, I get an error "Cannot set properties of null (setting 'innerHTML')"

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Jameson
  • 57
  • 5
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Heretic Monkey Nov 29 '22 at 19:13

2 Answers2

2

This is running immediately when the page loads:

let shopOutput = document.getElementById("shopOutput");

Since that #shopOutput element doesn't exist yet, the shopOutput variable will of course be null. And it will always continue to be null since it's never re-assigned.

If it doesn't need to be used until the function is invoked, set it in the function instead:

function addElements(selectElement) {
  let shopOutput = document.getElementById("shopOutput");
  // the rest of the function...
}
David
  • 208,112
  • 36
  • 198
  • 279
  • Do you maybe know why this might be happening: Inside the Ajax content is a Submit button which I would like to use to activate the shopOutput content. But when I click on the Submit button, the page reloads and the Ajax content disapears. – Jameson Nov 29 '22 at 19:43
  • @Jameson: It sounds like you're submitting a form. You can prevent the form submission in the JavaScript even handler, or remove the `
    ` element entirely if you're not using it, or change the button to `type="button"` to prevent it from submitting the form by default. Though this is all guesses based only on that description of the problem.
    – David Nov 29 '22 at 19:47
  • Yes that's correct, it was inside of a form element. Thanks for all your help @David – Jameson Nov 30 '22 at 09:45
-1

Anything that deals with a reference to an element should be contained in a $.ready() so that the browser waits before attempting to get references to things that don't exist yet.

$( document ).ready(function() {
    //your code here
});
Thomas Skubicki
  • 536
  • 4
  • 12
  • 1
    The document's `ready` event doesn't "wait before attempting to get references to things that don't exist yet". It executes when the document is ready. Which will still happen before any AJAX responses have been processed. – David Nov 29 '22 at 19:29