JavaScript Object extend div

1.3k Views Asked by At

As I am used to it from Java Swing, I tried to create a JavaScript object that can be added to the document itself. It should look something like:

var customDiv = new MyDiv();
document.appendChild(customDiv);

In the constructor of the object I would try something like

function MyDiv() {
   this.innerHTML = "test";
}

and the other stuff for the object.

So is it possible to create Websites in a way like this with JavaScript or how do you solve problems like this?

(I would like to create elements, that are an object and do everything themselves like handle Event Listeners and that can be added to the document.)

1

There are 1 best solutions below

2
On BEST ANSWER

You can, but similar to how Java Swing methods accept JPanels or other Swing Components, a function like appendChild accepts Node objects. You're sending in a function into appendChild, and how would it know how to accept it?

Examples of creating websites the way you describe:

var myDiv = document.createElement('div');
myDiv.id = "mydiv";
var myTextbox = document.createElement('input');
myTextbox.type = 'text';
myTextbox.value = 'some value';
myDiv.appendChild(myTextbox);
document.body.appendChild(myDiv);

So, you create the individual DOM elements and have a reference to them, similar to creating instance of Swing components. These elements can things like divs, which can be used similar to JPanels or input, similar to JTextFields. And then you use those references to combine them together to create a GUI.

To attempt to illustrate how document.createElement works, as you seem still confused in the comments, compare it to a Java method like this (Just FYI, it might not be strictly accurate, as I haven't used Swing in a while):

JComponent createComponent(string componentType) {
  if(componentType.equals("JTextField")) {
       return new JTextField(10);
    } else if(componentType.equals("JFileChooser")) {
       // return filechooser
    } 
    //etc.
}

As you can see, calling the method createComponent, and providing it a String value of what component you want, returns to you the actual instantiated empty component. You didn't define any constructors for it. Instead you place a reference to it, and do whatever you want with it.