0

I think I'm having another dumb moment. I've looked around for the past half hour, but Google searches aren't returning anything useful. I can't find the words to describe the issue I'm having. Here's my code.

function myElement(){

    this.init = function(){
        this.display();
    }

    this.display = function(){
        var element = document.createElement("div");
    }   
}

var myElement = new myElement();
myElement.init();

The issue I'm having is that the code (.createElement("div")) isn't working. I've messed around with it, and I've tried using other things too (such as JQuery's $.create('<div></div>'); method).

I'm not entirely sure if it's a scope or referencing issue.

(Please be aware that it's 02:10AM in the morning. My brain isn't in its most active state.)

2 Answers 2

1

It is working, but you're not doing anything with the div. I'm guessing you want to append it to the DOM:

this.display = function(){
    var element = document.createElement("div");
    document.body.appendChild(element);
};
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thanks for your answer. I would've accepted it, but MazeHatter got the same answer, just seconds before yours, therefore I've accepted his. +1 for including the whole function though, it's tidy. :D
0

You have to append the element to something, like another element, or the body.

 document.body.appendChild(element)

5 Comments

This will fail with an error, myElement is not a DOM element.
I thought this would work when I first saw your answer, but technology has other ideas. :( Uncaught TypeError: Cannot call method 'appendChild' of null
document.body.appendChild() is the method that adds elements to the body. Pass it your new element. So: document.body.appendChild(element)
Yeah, that's what I've done. I'm familiar with how object/methods/classes work, but I'm relatively new to JavaScript. Is there anything else that could be causing the error?
Ahh, never mind. I moved my code to the bottom of the page, and now it's working. Thanks!

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.