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

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.

Related

Get the first body tag in a document with multiple bodies

I have a html document containing an inline SVG with some <foreignObject>s in it. Those all have an own <body> tag.
Now I want to find the top <body>.
A simple solution would be
document.getElementsByTagName("body")[0]
but this seems to be inefficient (because it would first select all bodies and then drop all but the first) and I'm not quite sure if it's really reliable (is the ordering in such a set actually defined or may this change with other/newer browsers?)
Can see someone another way which is both efficient and reliable?
Your HTML document doesn't actually have multiple bodies as you allude to in the title, despite what the presence of body elements within the foreignObject elements might suggest.
Your HTML document still has only one body, its own body element, of which the foreignObject elements are descendants. This is always represented by document.body.
According to the documentation, getElementsByTagName:
Returns a NodeList of all the Elements with a given tag name in the order in which they would be encountered in a preorder traversal of the Document tree.
So, "is the ordering in such a set actually defined?". Yes, it returns the elements in the order they appear in the tree structure.
Reference: https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getElementsByTagName
You can use document.body element which returns the <body> element.
if you need the <html> element then the documenut.documentElement can be used

document.body.getElementById and document.getElementById difference

I am learning javascript from scratch. I am currently trying to grasp DOM.
I have a HTML page like this:
<html>
<head>
<title>javascript</title>
</head>
<body>
<h1>Welcome to javascript</h1>
Visit me here.
<p> <img id="image" src="kalam.jpg"></p>
<script type="text/javascript" src="code.js">
</script>
</body>
</html>
Now, I want to read a tags.
var links = document.body.getElementsByTagName("a")[0];
console.log(links.href);
It works fine. Now I want to read image.
var imageLink = document.body.getElementById("image");
console.log(imageLink.src);
But, the above code is not working.
I am getting an error:
Uncaught TypeError: document.body.getElementById is not a function.
Changing it to:
var imageLink = document.getElementById("image");
console.log(imageLink.src);
works fine.
My question is about the difference between document.body.getEl... and document.getEl..?
Does document.body reads only body part while document.getEl.. reads whole document including titles etc? If is it so then should not both the above code working?
document.getElementById() gets the element with the matching ID from the document.
document.body.getElementById() does not exist.
document.getElementsByTagName() gets all the elements which match the tag name from the document.
someOtherElement.getElementsByTagName gets all the elements which match the tag name and which are descendants of someOtherElement.
Since an ID must be globally unique within an HTML document, there is generally no need for the getElementById method to exist anywhere other than on the document object itself.
getElementById is a function of document object (so it simply doesn't exist in document.body)
getElementsByTagName is a function of any dom element (including document.body).
Using document.getElementById you are retrieving a specific element with the specified ID on the page. IDs should be unique to each element on a page. when using document.form (or whatever) you are 'filtering down' your selection.
I think if you're new to this it might be worth using
document.querySelectorAll('a')[0]
document.querySelector('#image')
document.querySelector('.someclass')
just because it does tag, id and class all in one.

Is an element attribute a node or not?

According to http://www.w3schools.com/js/js_htmldom_navigation.asp tutorial, element attributes are also nodes. In the example below, script is showing only element nodes.
<!DOCTYPE html>
<html>
<body>
link
<p id="demo"></p>
<script>
var n = document.body.childNodes;
var s = "";
for (var i = 0; i < n.length; i++)
s += n[i].nodeName + "<br>";
document.getElementById("demo").innerHTML = s;
</script>
some text
</body>
</html>
The result (node names) is:
#text
A
#text
P
#text
SCRIPT
I guess #text is node name for line breaks etc (but I have no idea why text after SCRIPT is not shown as #text).
Why it's not showing href attribute? Even when I try to see all child nodes of anchor element, it's showing only text node inside.
tl;dr: Yes, they are nodes, but they are treated differently.
From the DOM spec:
Attr objects inherit the Node interface, but since they are not actually child nodes of the element they describe, the DOM does not consider them part of the document tree. Thus, the Node attributes parentNode, previousSibling, and nextSibling have a null value for Attr objects. The DOM takes the view that attributes are properties of elements rather than having a separate identity from the elements they are associated with; this should make it more efficient to implement such features as default attributes associated with all elements of a given type. Furthermore, Attr nodes may not be immediate children of a DocumentFragment. However, they can be associated with Element nodes contained within a DocumentFragment. In short, users and implementors of the DOM need to be aware that Attr nodes have some things in common with other objects inheriting the Node interface, but they also are quite distinct.
As the text says, attribute nodes are not considered to be children of the element, hence they are not contained in childNodes. To get the attributes of an element, you can access element.attributes.
Element attributes are not nodes.
If you check MDN about .childNodes (wich is a far better source that w3schools) you will read:
The Node.childNodes read-only property returns a live collection of child nodes of the given element.
In the DOM3 spec one can read:
Attr objects inherit the Node interface, but since they are not actually child nodes of the element they describe, the DOM does not consider them part of the document tree.
About your other question, the reason why you do not see the text after the <script>tag is because the DOM is not ready loaded yet. If you put that code in the end, near </body>, then everything will be there.

iFrame nested in iFrame with same ID

I'm using the frameElement.id JavaScript property to make some changes to the page when nested in a particular iFrame.
There is a case where I have an iFrame with that ID nested in an iFrame with that ID. So it looks like:
Main Page:
<body>
<iframe src="url.htm" id="show_body_only"></iframe>
</body>
url.htm:
<body>
<iframe src="url2.htm" id="show_body_only"></iframe>
</body>
Just wondering if this is semantically correct.
Please do not berate for all the iFrames, I had little choice.
As far as CSS, the spec says:
no two such attributes can have the same value in a conformant document
If the frames explicitly share stylesheets, then the IDs will be applied separately since each frame is its own document.
As far as the DOM, the spec says:
The getElementById(elementId) method must return the first element, in tree order, within context object's descendants, whose ID is elementId, and null if there is no such element otherwise.
A node's node document can be changed by the adopt algorithm.
If the frame nodes are imported and adopted, then getElementById returns the first match.
References
CSS3: ID Selectors
DOM4 Concepts: node document
Document.adoptNode()
DOM4 5.2.2: Interface NonElementParentNode

Help me understand objects in DOM

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.

Categories

Resources