0

I'm trying to write a short javascript function to add buttons for prev/next to a css-slider I've put together.
I don't have access to the DOM, so figured I'd just insert the div's via javascript. Here is the function:

function createfn(){
  var element = document.createElement("div");
  var prev = document.createTextNode("<");
  element.appendChild(prev);
  document.getElementsByClassName("sqs-gallery")[0].appendChild(element);
}
window.onload=createfn();

I am getting an error:

"Cannot read property 'appendChild' of undefined"

The div container with class .sqs-gallery is definitely appearing on the page. I was questioning whether this was somehow running before the DOM fully loaded, but I have the window.onload in there which (I believe) should wait until everything is loaded before running the function.

Any and all thoughts and help is greatly appreciated!

4
  • As you've described the situation, it should work. Try adding a minimal reproducing example to your question. Commented Aug 14, 2019 at 19:32
  • Does an elements with class name sqs-gallery isset? Commented Aug 14, 2019 at 19:32
  • 7
    Get rid of the parentheses here: window.onload=createfn() Commented Aug 14, 2019 at 19:34
  • * What is the full error returned in console? * Have you tried to console.log your variables and what's the results? Commented Aug 14, 2019 at 19:40

2 Answers 2

5

You perform window.onload=createfn();

it means that you assign result of createfn() to onload (not the function). And function "createfn" being executed immediately (does not wait for window loading).

Just remove parentheses to assign handler instead of function value.

Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick! Figured it was a stupid mistake like that! Thanks for the quick responses.
1

If you leave the code as window.onload=createfn() (with the parenteheses) createfn will run directly as the code starts to run (even before the DOM has loaded) because the result needs to be assigned to window.onload.

What you instead should be trying to do is assign the function, not the result: window.onload=createfn. This should work just fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.