Home > Net >  How do i resolve "Cannot read properties of undefined (reading 'ownerDocument')"
How do i resolve "Cannot read properties of undefined (reading 'ownerDocument')"

Time:12-27

I am trying to add a div inside the main div on page loading, it works when i write the code like this:

function DivAdder() {
  $('#mainDiv').append('<div ></div>');
}
DivAdder();
window.onload = DivAdder;

But i want to make this function have a parameter so i can just pass its name instead of writing the whole string in .append function. I wrote something like this but i am having the error from the title:

function DivAdder(variable) {
  $('#mainDiv').append($(variable));
}
DivAdder('<div ></div>');
window.onload = DivAdder;

And i tried this as well:

$('#mainDiv').append(variable);

But nothing happens. I read some documentation but was not successful. Appreciate the help <3 .

CodePudding user response:

When you are using $('#mainDiv'), remove the hash(#) - hence change the particular line to: $('mainDiv').

When you try to fetch the ID, don't use hash(#), instead use the name of the ID only.

Also remove the line for window.onload, because the function DivAdder() will do the required job for you when the page is loaded and the script is executed.

CodePudding user response:

This is because window.onload passes an Event object as first argument. If you console.log(variable), it will tell you it's an Event.

You need to keep this first argument as an optional event, and pass your HTML as second argument :

function DivAdder($event, html) {
  console.log("Event = ", $event)
    console.log("Adding div : " , html)
  $('#mainDiv').append(html);
}
DivAdder(null, '<div >TEST</div>');
window.onload = DivAdder; // This will call DivAdder( LoadEvent )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv"></div>

I'm not sure why you're assigning window.onload = DivAdder in the first place, since this won't add any HTML and won't do anything at all. You can get rid of it completely, it's only causing trouble.

function DivAdder(html) {
    console.log("Adding div : " , html)
  $('#mainDiv').append(html);
}
DivAdder('<div >TEST</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv"></div>

  • Related