DOM vs scripting language - javascript

I am not aware about the relationship between scripting language and Document Object Model as exactly
All we know that DOM is an API for HTML and XML document to manipulate as objects generated by document structure tree , so API has propriety and method which we can use them to control changes in a document but if we say that we will find finally there is no any intervention for scripting language like JavaScript
for example in case we type this line in our HTML document :
document.getElementById("demo").innerHTML = "Hello World!";
we will find just DOM API ( method and propriety ) , no any trace for JavaScript
what is relationship between DOM and JavaScript , why always appear together while I am not feel trace of JavaScript , if scripting take place in HTML document all I find API DOM tool ( method and propriety ) , I could not able to touch JavaScript working in our HTML document

Despite the fact that this post is currently at -3 points and poorly phrased, I think I can suss out the question the poster is asking and will try to answer it. Hopefully the community won't punish me for answering on a negatively scored question.
Yes, you clearly have some confusion around the definition and relationship between what constitutes the JavaScript language and what constitutes the DOM API.
JavaScript is a programming language. It has functions, inheritance, variables, operations, etc etc.
function addTwo(num) {
return num + 2;
}
var eight = addTwo(6);
console.log(eight); // logs 8
It has some cool features that some other languages don't, like functions as first-class citizens. We won't cover that here.
While JavaScript can run in a few different environments, it was originally written for the purpose of scripting in web browsers. It is the only scripting language that the browser can execute (with probably a few exceptions not important here). The DOM (Document-Object Model) is the interface by which JavaScript can interact with the document and nodes being shown in the web page. It allows you to get elements on the page, manipulate them, create them, delete them, etc. When you are interacting with the DOM, you are doing so in JavaScript. It is simply an API available to JavaScript for manipulating the document, not a separate language unto itself.
Hopefully this clears things up for you. Also note that JavaScript is not relegated to the browser-- the most common other environment for JavaScript is NodeJS, which allows for all sorts of fun stuff like tooling or writing your backend code with JavaScript.
This page from the Mozilla Developer Network characterizes the distinction elegantly:
...it's written in JavaScript, but it uses the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements).
(Also, the world is probably not as 100% black and white as I have spelled it out here. There are probably edge cases in which other languages can be made to run in a browser, or perhaps there is some way to interact in the DOM with Web Assembly, which is relatively new to the scene. I'm just spelling out here the simplest case that probably covers the vast majority of scenarios existing today. However, this page from MDN does give an example of interacting with the DOM using Python.)

Related

Are document.URL and location.href considered part of the DOM?

Simply put, are document.URL and location.href considered part of the DOM (Document Object Model)?
The "DOM" (Document Object Model) is the name for the entire standardised in-browser API - not just the part that's concerned with the actual HTML document (i.e. [window.]document) - it also includes the window, navigator, and location objects.
Granted, many parts of what's available to you in JavaScript are not part of the DOM, namely JavaScript's built-in library, such as String, Array, parseInt, and so on - and given that people generally learn both JavaScript and the DOM at the same time it's often very hard to tell them apart.
There are also pseudo-standard components that are not officially part of the DOM (until recently, or post-facto or defacto standardisation), such as XMLHttpRequest (originally a Windows/IE-only COM component exposed through Microsoft's proprietary ActiveXObject JScript API).
...but the DOM is not always available in JavaScript, you can use JavaScript as a shell-scripting language (e.g. Windows Script Host), or in server roles (Node.js) - there's no document and navigator element there, for example (though strictly speaking, there are "server-side DOMs" used for generating markup dynamically).
And conversely, you can have the DOM without JavaScript: the DOM is simply an API specification, there are implementations for Java, .NET, and others. The DOM was originally designed for both Tcl and JavaScript, for example.

Using Script Tags As A Template System

** Revised **
I made this basic example which I believe is evicence that JavaScript may be useful as it's own template engine:
http://jsfiddle.net/julienetienne/u6akrx7j/
<script>talk[0].text('Hello World!');</script>
It's just a simple example but as you can see there are many possibilities eg.
It doesn't necessarily have to detect the tag nodes in that manner, it could do it by class, id. It is also possible to obtain the script node of the function,
you could simply print variables like p('Page Title');
A self closing list of elements could be similar to e.g. li('', menu);
And you could clearly build up other complex data sets as you can with any other common template engine.
Before this edit I made the mistake of comparing it to PHP. I'm actually considering it more of an alternative to e.g. handlebars, underscore, moustache, dust and similar.
But before I get to excited I would really like to know if there are any issues in regards to using in this way. (I'm not concerned with novice best practices).
The benefits of an organic template system seems quite apparent. The biggest advantage is that there is no syntax to learn and it's cleaner than seeing %{{foobar}}% like markings.
Considering my example is just a tiny minimalistic concept, please tell me the drawbacks of a system like this compared to common template engines.
Thanks
It looks like it's a PHP-style templating system, but it is apparently not:
In the fiddle the script parts could be written anywhere in the page.
The part that defines the position of the texts to be inserted into the DOM is defined by the line var talk = document.getElementsByTagName('div'); and the structure of the HTML.
If you'd use more div than the ones already there the texts will appear at a totally different (and supposedly wrong) position.
The disavantage will thus be, that you can't use the system independently of the underlying markup. That makes it different from a use case in PHP, where you can echo the variables by defining their position in the markup.
Have a look at Angular or similar front end frameworks, if you are looking for a way how to implement a templating system.

javascript objects vs DOM objects

this is maybe a stupid question, but when I search for an answer I get jQuery results that talk about object arrays. I'm not there yet and want to understand how javascript itself is interacting with the DOM.
The DOM is an object tree created and used to render HTML if I'm not mistaken? And javascript has objects of the same name. For example: window, document, and elements with id... Are these the same objects?
I've read that javascript is part of HTML5, is this because the javascript objects are in fact the DOM objects and that the javascript language has been built up around the DOM? If so, how could it ever be possible to use javascript without the DOM? - For example, how could you ever make a desktop app? I use a program called brackets which is coded in javascript.
I think MDN has a great definition:
The Document Object Model (DOM) is an API for manipulating HTML and XML documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation by using a scripting language such as JavaScript.
So the DOM is the specification of an API which can be used to select, manipulate and create new elements in a webpage, via an API.
That API is made visible (or exposed) to us, JavaScript developers, by allowing us to access JavaScript objects which implement particular parts of the DOM API.
The window element is one of those; as MDN says
The window object implements the Window interface, which in turn inherits from the AbstractView interface.
window is the JavaScript object window.
... it implements the DOM Window interface
... which, behind the scenes (we don't really care about this) inherits the AbstractView interface.
However, as well as implementing the DOM Window interface, window also exposes several JavaScript types and functions; which are not part of the Window interface, but exist on the window object.
All the types; window.String, window.Object, window.Array.
Math
...
As you specifically mentioned document; document is part of DOM Window interface, which you can see listed here.
In short, anything which involves selecting, manipulating and creating HTML elements will usually be part of the DOM.
HTML5 is the latest HTML standard which add new HTML elements such as <audio> and <video> tags. The DOM API has been updated to allow those new elements to be controlled by the API.
In turn, the JavaScript objects which implement those API's have to be updated.
JavaScript is a programming language. The DOM can be thought of as a framework or library which lets you control HTML from JavaScript.
JavaScript can be used completely standalone, without this library; which is exactly what happens in environments such as NodeJS and Brackets.
Take it this way:
You need an environment and a program.
The environment is the browser
The program has :
an interface( web page aka document)
code (javascript)
So you end up with 3 object models
DOM document object model
BOM browser object model
JOM javascript object model
The following graph may help:
http://javascript.info/tutorial/browser-environment

what exactly is the DOM? and what is an object as taken from the DOM?

I know a bit of Javascript and have recently started trying to tie it into HTML with the code academy course. in the following code:
function sayHello(name){
document.getElementById("result").innerHTML = 'Hello ' + name + '!';
}
The "document" in the above code is the DOM?
That would mean that getElements is a property (function) of document, and that innerHTML is a function of the getElements function.... right?
If I am seeing this correctly, how is it possible that DOM objects have javascript properties/functions?
Is document the DOM
Short answer
Yes, in the sense that it is the root of it.
Slightly longer answer
The Document Object Model (DOM) is what the browser exposes to the JavaScript runtime to allow JavaScript code to manipulate the page (its nodes and associated metadata). document is one part of the DOM.
How can the DOM have JavaScript properties
Short answer
They don't.
Slightly longer answer
The DOM is not actually managed in JavaScript (yet). It is typically managed by a separate engine altogether, written in a lower-level language like C++ or Rust (in the case of Mozilla's Servo project). The JavaScript runtime is also written in a lower-level language (again, C++ is most likely) and certain attributes of the DOM are exposed to the JavaScript runtime as if they were native JavaScript objects. The fact that they are not makes all kinds of interesting things possible ... and generally make it so that these DOM objects do not always behave as you would expect "real" JavaScript objects to behave (for example typeof querySelectorAll in IE 8 returns "object", not "function" as one would reasonably expect).
the Document Object Model is a model for interacting with HTML. They do not have "javascript properties" or "functions", javascript functions are executed on HTML elements which are found through the DOM.
getElementbyID
is a function in javascript, which retrieves a HTML element based on the DOM. Below is what the DOM looks like, and is how javascript will execute the aforementioned function.
http://www.w3schools.com/js/js_htmldom.asp
Close. document is the root element in the DOM, or Document Object Model. The DOM is the in-memory representation of the current document.
Calling document.getElementById() returns an HTML element, which has the property innerHTML. Writing to innerHTML tells the browser to render the string as that element's children.
DOM objects do not have javascript-dependent properties or attributes. Javascript is just one way of accessing DOM attributes.
DOM can be thought as an Interface (provide by layout engine like Gecko in Google Chrome and Firefox ) between the HTML and Any_Other_language
{like JavaScript} that want to use the html.
Say Tomorrow If a new language is born ( something similar to javaScript but a new language that has it's engine implemented in the browser like JavaScript has V8 engine in Google Chrome ) that want to play around with HTML, then just to access the HTML they don't have to write some hefty low level code( inside the engine for this language ) instead they can use DOM_Interface ( inside the browser ) to access and this makes it easy for them to concentrate on their logic.
DOM is Document Object Model ie your whole document is the hierarchy of objects with Window being the parent of all.
It provides a structured representation of the document (a tree) and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content.

What are the use cases of jsdom

After reading this Micro templates are dead article. I've become curious:
Whether Using the DOM on the server results in cleaner more maintainable code then templating.
Whether it's more efficient to use jsdom instead of a templating engine.
How to factor jsdom into the View of a standard MVC setup.
And generally in what situations would it be better to use a server-side DOM abstraction, like jsdom rather then a templating engine, like EJS or jade.
The question is specific to node.js and other SSJS
Well, I actually needed JSDom for a small project I built over the weekend in node.js. So, on my server, I had to accept a URL to fetch, grab all of the HTML from the given URL, parse it, and display images to the user so that the user could select a thumbnail from that URL. (Kind of like when you drop a link into the Facebook input box) So, I used a module called Request which allows me to fetch HTML on the server-side. However, when that HTML reached my program, I had no way to traverse it like you do with client-side javascript. Because there was no actual DOM, I couldn't say document.getElementById('someId'). Therefore, JSDom came in handy by giving me a "makeshift" DOM that allowed me to traverse the returned HTML. Now, even though I was still on the server side, JSDOM created a window object very similar to the window object in the browser, and created a DOM out of the returned HTML. Now, even on the server, I was able to get all images by calling window.$('img'). I could target and parse the elements like normal. So, this is just one problem where JSDom turned out to be the solution, but it worked amazingly well. Hope this helps some!
Its a nice abstraction that matches a client side engineers take on how the dom is built and modified. In that respect it is 'cleaner' because there is one mental model. Its also nice because we don't have to mix a kluge of disparate syntaxes from a templating language on top of otherwise clean declarative markup as is the case with even the 'stupidest' templating system, such as mustache.
I would NOT say its more efficient to use jsdom for templating. Go take a gander at google wrt to 'memory leaks with jsdom' for instance. jsdom is rad, and is super useful for tasks like weekend projects for crawling sites, doing non-server related tasks, but I think its slow as shit from a high performance web server perspective.
There are a billion ways to factor this. No method has emerged as a 'standard' way. One way that I've seen is to send down an empty 'template', i.e. a block of html that represents a model in some way, and then use that to bootstrap building your end view from a model. From that article, for example:
<li class="contact" id="contact-template">
<span class="name"></span>
<p class="title"></p>
</li>
This is the 'view' in the classic respect. In the typical web application, it might look something more like:
<li class="contact">
<span class="name"><?= $name ?></span>
<p class="title"><?= $title ?></p>
</li>
To use mvc, one sets up a controller that is vaguely aware of the semantics of the above view and the model it represents. This view is parsed into the/a DOM and accessed via your favorite selector engine. Each time the model this represents changes, you might use change events or callbacks to update the view. For instance:
Lets imagine that 'model' fires a 'change' event every time a property changes.
controller = new Controller({
view: $('#contact-template').clone(), // Assume jquery or whatever
model: aContact
});
// Assume some initialization that sets the view up for the first time
// and appends it to the appropriate place. A la:
// this.view.find('.name').text(model.name);
// this.view.find('.title').text(model.title);
// this.view.appendTo('#contacts')
controller.on('model.name.change', function(name){
this.view.find('.name').text(name);
});
These are what systems like Weld and Backbone.js do for you. They all have varying degrees of assumptions about where this work is taking place (server-side, client-side), what framework you're using (jquery, mootools, etc), and how your changes are being distributed (REST, socket.io, etc).
Edit
Some really useful things you can do with jsdom revolve around integration testing and spidering:
https://github.com/mikeal/spider - general purpose web spider that makes use of node's event based processing and gives you jsdom/jquery to help you easily access the DOM in a programatic way
https://github.com/assaf/zombie - headless browser testing using jsdom/jquery for integration tests
https://github.com/LearnBoost/tobi - similar headless browser testing
Personally, I'd like to see a project that took tobi's approach, but mapped it on top of something like https://github.com/LearnBoost/soda such that we can do cloud based selenium testing without selenese (since imo, it sucks).
A few come to mind:
Sharing views/controllers between server and browser
Data mining / crawling / processing
Transformation for fragments of HTML used in AJAX/realtime stuff
Absolute separation of logic and content by avoiding template tags
And to answer your questions:
maybe. A lot of things affect code quality, but it's a step in the right direction
nope, templating engines will always be faster, since they can pre-compile templates
this probably warrants a new question?
point 2 of your question can be answered by this templating testcase:
go http://jsperf.com/dom-vs-innerhtml-based-templating/300
click the button "Run tests".
be patient, it compares weld vs. a lot of other template engines and gives you the current benchmarks ...

Categories