Help me understand objects in DOM - javascript

I have a question about DOM objects.
What I have learned is that everything in a document are objects?
<form name="myform" action="script.js">
<input type="text">type something</input>
</form>
If we look at the example, is form an object with properties name and action?
But are name and action themselves also objects? i don't quite understand the difference between objects and properties.
And what is the difference between object element and node?
I know basics of html, css, javascript and dom. but can someone describe the big picture for me here how these parts are communicating with each other.
because there are so many elements, properties and methods. so im all lost

Seems to me your trouble is not understanding the concept behind object-oriented programming. JavaScript is an object-oriented language. You should probably take a quick tour of the concepts.
Briefly, though, objects are a way to encapsulate both data (the "properties" you are referring to) and functionality (the "methods" or "functions" you can ask an object to perform).
In the case of the JavaScript DOM, there is a tree of objects, where each object contains properties that are, themselves, objects. So you can have a Form object with methods like onSubmit() and properties like "elements", which is an array of form fields. Each element in the array is another object, like perhaps a TextField object or a Checkbox.
So now you know about objects. One thing about objects is that they can inherit properties from a parent class of object. For example, in JavaScript, there is an Element class and each of the form field objects is an instance of a "subclass" of the Element class. So, since Element defines the "name" property, and TextField and Checkbox and all their friends inherit from Element, they all automatically have this "name" property available too.
The term "node" refers to a particular location in a tree or graph structure. In this case, the DOM (Document Object Model) defines the types of objects that are allowed to be nodes in the tree that represents the webpage. For each webpage you visit, the browser constructs a "DOM tree", which is a big tree of objects representing each of the elements in the webpage.
Notice that HTML is naturally in a tree-like structure: the html tag contains head and body, the head tag contains title, meta, and script tags, the meta tag contains attributes like name and content. All this is arranged by the browser into a tree of objects, and that is what you are manipulating when you use JavaScript to do DOM programming.
So to recap: objects are the fundamental representation of data and functionality in JavaScript. Elements are particular classes of object that are subclasses of the "Element" class, and which represent some kind of form field. These can be found in the form.elements array, which is a property of the form object. Finally, nodes are points in the tree of tags, text, script, and other objects that make up a webpage.
Hope it helps!

I've taught people about the DOM before and found that seeing the DOM in action.
Go get firebug, if you don't have it.
http://getfirebug.com/
After you of course restart Firefox...
Open up any web page and right-click on something, there will be an option called "Inspect Element". This will display the rendered code of the page. When I say rendered I'm referring to the page after it has been modified by any javascript, different from the standard source code which is just the straight HTML sent from the server.
The element which you are inspecting will be highlighted. Now, right click on that highlighted element and select "Inspect in DOM Tab".
Once you're in the DOM tab, this shows you all of the properties of the element you inspected. In here you may see attributes of the element like type="input", methods of the element like focus(), maybe custom prototypes, Firefox proprietary attributes, and much much more.
Here are some methods, functions, and attributes on your need to know list, look these up in the Mozilla Developer Center. Spend some time writing scripts which move you around the DOM and allow you to alter it using these, don't use innerHTML to do anything.
createElement
createTextNode
appendChild
insertBefore
removeChild
cloneNode
setAttribute
removeAttribute
getElementById
getElementsByTagName
childNodes
firstChild
lastChild
nextSibling
hasChildNodes
tagName
attachEvent (IE) / addEventListener (all others)
detachEvent (IE) / removeEventListener (all others)

HTML attributes are exposed as
properties on the element object.
http://www.w3.org/TR/DOM-Level-2-HTML/html.html
http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614
Element = object, property = attribute. A method is just an invocable property, eg onclick.
<form
onsubmit="alert('hi');"
id="contact-form"
>
onsubmit is a method, id is a property, form is a node with a node type of 1 which means it's an HTMLElement and inherits generic HTML properties.

in your example, the name and action are attributes of the form object.
if you had something like this in a JSP page
<form name="frm" action="somepage.jsp" onSubmit=" return validateForm();">
<input type="text" name="txtField" id="txtField"></input>
<input type="submit" value="submit"></input>
</form>
and a js function defined like so that checks to see if any text was entered into a text box.
<script>
function validateForm(){
if(document.frm.txtField.value="")
return false;
else
return true;
}
</script>
you can use the document object to access the form object in the dom and from that access the input element held by the form.

Related

In javascript is this a valid construct?: document.name.name.value?

Here's the form:
<form name=fname ...
<input name=iname value="" ...
This javascript function obtains the value of the input with:
var val = document.fname.iname.value;
Is that legit? I thought you had to do this with getElementsByName. It works, it's just I've never seen anyone do it that way. Is this one of those things that just happens to work... for now?
UPDATE
According to WHATWG 6.2.4 Named access on the Window object
The Window object supports named properties. The supported property names of a Window object window at any moment consist of the following,...for all applet, embed, form, frameset, img, and object elements...
According to W3C DOM 2 HTML Specification 2.7.2.1 HTMLAllCollection
The following elements name attribute can be referenced as a property of the document object:
anchor, applet, button, form, frame, iframe, img, input, map, meta, object, param, select, and textarea
This referencing approach is standard, but it's use is generally discouraged. A few reasons to avoid directly referencing DOM property or window object by name attributes are: variable shadowing, inadvertently scoping to the window object, major browser inconsistencies, etc. For details on why it should be avoided, read this section and this post.
This Snippet shows a stable and standard way of using form names as a reference document.forms and the referencing form names previously mentioned as well.
SNIPPET
var val1 = document.forms.fname.elements.iname.value;
console.log(val1);
var val2 = fname.iname.value;
console.log(val2);
<form name='fname'>
<input name='iname' value="42">
</form>

html element - property of document object ? or an object?

so, html elements such as <title>are sometimes referred as property, but sometimes they are referred as objects. i am kinda confused. are html elements properties of document object? or are they objects? or are they both at the same time? thanks. to make question meet quality standards i will add some random codes.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
The document itself is a document node.
All HTML elements are element nodes.
All HTML attributes are attribute nodes.
Text inside HTML elements are text nodes.
Comments are comment nodes.
In the HTML DOM, the Element object represents an HTML element.
DOM w3schools
The document object has a title property, which is a string, which is an object. But the document object does not have direct properties for the html elements in the page, that's why you have accessor functions like document.getElementById('id'), which return objects representing html elements. Open up a console in chrome and type document. to see all the properties the document object has. Also see that document.title and document.getElementByTagName('title')[0] do not return the same thing.
The DOM, or Document Object Model is a tree. The HTML document available at window.document is the root node of this tree.
Essentially everything else in the document is a node somewhere in this tree, whether it is an element like <p> or an attribute node like class="foo" or a text node. Each of these nodes are objects that you can interact with via Javascript.
They are two separate things.
Element is the HTML element or tag.
Javascript and jQuery (which is also Javascript), for example, modify and control the HTML elements by using the HTML DOM (HTML Document Object Model). The DOM contains the Objects you're referring to. Each DOM object refers to an element and when the Javascript modifies your HTML page, it's actually accessing the DOM, not the HTML elements.
Take a look at: http://www.w3.org/TR/DOM-Level-2-Core/introduction.html.

Functionality of Javascript functions and jquery selectors from within html

I have this javascript function:
function clearDiv(div_id) {
alert(div_id);
$(div_id).empty();
}
And the following html:
<input value="Clear" type="button" onClick="clearDiv(div_to_clear)" />
<div id="div_to_clear">
<!-- more html -->
</div>
Why is it that the above will actually find the javascript div object with id div_to_clear and use the $ selector to access it?
If I had done the input as :
<input value="Clear" type="button" onClick="clearDiv('div_to_clear')" />
I would need to change my function to
function clearDiv(div_id) {
alert(div_id);
$('#' + div_id).empty();
}
Is there any documentation about this? Are there advantages to using one method or the other?
IE (and Chrome in an effort for compatability) will create properties on the window with names of elements with ids, corresponding to those elements.
In the first example are are passing window.div_to_clear which points to your element directly. In the second, you are passing a string telling jQuery which element to select.
The first one is non-standard behavior so you should not rely on it.
The first one is actually a browser bug (they called it a feature) to access the DOM node by window.div_to_clear (the global variable) - and jQuery creates its wrapper around the element. For legacy reasons, it still exists in current browsers, but is deprecated. Your really should use the selector solution.
This is because there is a widely-implemented (although not best practice) method by browsers to automatically place html elements with id's into their correlating variable name. For example:
<div id="someId"></div>
will end up psuedo creating the variable someId which holds that html element.
These questions have similar information on the behavior:
Do DOM tree elements with ids become global variables?
Where does the variable holding an element with an id get stored?
Element accessible with ID
Here is a jsperformance test showing that accessing the id in that manner is slower than using document.getElementById: http://jsperf.com/global-id-vs-document-getelementbyid

How does JavaScript know where an element is the DOM?

I was writing some code in jQuery, like:
$(".middleContent").not(this).slideUp();
(this = currently active .middleContent element)
And I was wondering how JavaScript knew the elements index in the DOM.
I know each object is unique, but if you have a few elements with the same class how does it distinguish between them? It is to do which its index in the tree of all the elements, like how a program has an address in RAM?
Each dom element is an individual object and unique. The not does comparisons on the current execution context ( this ) to make sure that any element inside the array doesnt equal this.
I think you're underestimating what it means for a DOM element to be unique. It's not only the class, tag name or index within the current parent element that identifies a DOM element. Each DOM element internally has a unique identifier, which is not accessible to you. It's used by the browser to organize the DOM internally. There can be hundreds of seemingly identical <div class="middleContent" /> elements in your page, each single one has a unique internal identifier. If you compare one DOM element to another, the browser will always be able to tell whether it's the same element or one that just looks like it.
this refers to one specific DOM element, therefore jQuery is able to filter it out of a collection of seemingly similar elements.
The elements in the DOM are just objects themselves, organised into a tree structure, so they have next and previous siblings at the same level, their own list of children, a parent. From this you can walk around the structure of the tree and manipulate it.
You can obtain the object(s) inside a jQuery object by using indexing notation:
var caption = $('#caption');
var domElement = caption[0];
Then domElement will contain one of these.

Javascript focus() and select() quirk

Im working on a form and getting null or not an object errors in ie.
<form action="#" method="post" name="adv_search">
<input class="inputbox" type="text" name="keyword1" value="none" id="keyword1"/>
</form>
<script>
document.adv_search.keyword1.focus();
document.adv_search.keyword1.select();
</script>
//whereas if I use
<script>
var key1 = document.getElementById('keyword1');
key1.focus();
key1.select();
</script>
//everything is fine
i would like to understand why.
i would like it to work without having the id tag for the input field
thanks in advance
shouldnt the document.formname.fieldname.focus();
and document.formname.fieldname.select();
work?
Your particular example works for me, but if I add another field with the same name:
<input type="text" name="keyword1" />
<input type="text" name="keyword1" />
Then document.adv_search.keyword1.focus() will fail with the error you specify.
The reason is that:
document.adv_search.keyword1
is a shortcut for this syntax (which goes back to DOM Level 0 and the Netscape 2 days!):
document.forms.adv_search.elements.keyword1
(Incidentally, it is better to use this full syntax, instead of relying on the behaviour of the ‘document’ and ‘form’ objects being indexed on names: if a new method is added to HTMLDocument or HTMLFormElement, that might clash with the control name you are using. This is less of an issue when you use the document.forms or form.elements collections. Also, IE mistakenly dumps all names and ids into ‘document’, so if you've got an element with id="adv_search" in addition to the form with that as a name, document.adv_search will return the wrong one.)
Anyway, the DOM Level 0 scripting methods behave slightly curiously when you access an element by name like this. If there is a single matching element, you'll get that one as a standalone object. If, on the other hand, there are more than one, you'll get a list of objects. You can't call focus() or select() on an array-like list, which is why the error appears; you'd have to do something like keyword1[0].focus() when the list was returned.
So you have to decide whether you're going to be using old-school DOM Level 0 methods to access your form controls — in which case you're going to have to cope with sniffing for single-or-multiple-controls — or move to the ID-based methods introduced by ‘DOM Level 1’:
document.getElementById('keyword1').focus();
The ID-based methods are generally a bit more typing (in the script and to add ‘id’s to all elements you wish to access this way, if they don't already have them), but they are simple and unambiguous. (Also you can then drop the name on the <form> itself.)
The ID approach really is best but if you want to go by name, use getElementsByName.
In this case, it might look like this:
<script>
// retrieves array of objects with the name 'keyword1'
// and takes the first one
var key1 = document.getElementsByName('keyword1')[0];
key1.focus();
key1.select();
</script>

Categories

Resources