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.)
You can, but similar to how Java Swing methods accept
JPanel
s or other Swing Components, a function likeappendChild
accepts Node objects. You're sending in a function intoappendChild
, and how would it know how to accept it?Examples of creating websites the way you describe:
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
div
s, which can be used similar toJPanel
s orinput
, similar toJTextField
s. 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):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.