document is an alias name? - javascript

Is document an alias of Sys.UI.DomElement in JavaScript?
I have come across this example in msdn.
$addHandler(Sys.UI.DomElement.getElementById("Button1"), "click", toggleCssClassMethod);
I used to see only document.getElementById(id). So raised this question.Itmight be sound bad. But I am just kid in JS world.

No, the two are not the same. I think your confusion is probably coming from the common misconception that getElementById is a function only belonging to document. In fact, you can use getElementById on other DOM elements. Something like this works just fine:
document.getElementById("test").getElementById("test2")
http://jsfiddle.net/CNc2s/
Notice that the 2nd call of getElementById is being called on the DOM element returned by the first call. This will find an element with an id of test2 within an element with and id of test.
The reason you don't often see things like this is that ids must be unique within a document. So calling it on the document will get the same element as calling it on a containing element.

No, document is not an alias for Sys.UI.DomElement. This can be demonstrated with a quick experiment in the IE javascript console.
document.name = "hello";
console.log(Sys.UI.DomElement.name); // Prints undefined

Related

Why can't I use element.remove() on an element created with createElement() if I do something in between in the DOM? [duplicate]

When creating elements via code, I have encountered an issue where modifying the innerHTML property of an element breaks any references to other elements that are injected into the modified element prior to the modification.
I have a test case here: http://jsfiddle.net/mJ7bF/1/ in which I would expect the link1 reference to behave exactly as link2 does.
This second test case is the same code, but instead of using the innerHTML property to add the <br> tag, I create the line break with an object. This test behaves as expected: http://jsfiddle.net/K4c9a/2/
My question is not regarding this specific code, but the concept behind it: what happens to the link1 reference in that first test case? If it doesn't refer to the HTML/DOM node that is visible when the cont node is injected into the document, what DOES it refer to, and how does this fit in with the ByReference nature of javascript objects?
few things here.
first of all. strings are immutable hence doing element.innerHTML += "<br>" acts as a complete read and rewrite.
second, why that is bad:
aside from performance, mootools (and jquery, for that matter) assigns special unique sequential uids to all referenced elements. you reference an element by calling a selector on it or creating it etc.
then consider that SPECIFIC element with uid say 5. the uid is linked to a special object called Storage that sits behind a closure (so its private). it has the uid as key.
element storage then works on a element.store("key", value") and element.retrieve("key")
and finally, why that matters: events are stored into element storage (eg, Storage[5]['events']) - do element.retrieve("events") and explore that in fireBug if you're curious.
when you rewrite the innerHTML the old element stops existing. it is then recreated but the event handler AND the reference to the function that you bound earlier will no longer work as it will now get a NEW uid.
that's about it, hope it makes sense.
to add a br just do new Element("br").inject(element) instead or create a templated fragment for the lot (fastest) and add in 1 big chunk, adding events after.
HTML is represented internally by a DOM object structure. Kind of like a Tree class in traditional programming languages. If you set innerHTML, the previous nodes in the parent node are destroyed, the new innerHTML is parsed, and new objects are created. The references are no longer the same.
div
|-- a..
The div object above contains an Anchor object as a child. Now set a variable link1 as a reference to the address of this Anchor object. Then the .innerHTML is += "<br />", which means all of the nodes of div are removed, and recreated dynamically based on the parsed result of the new value of .innerHTML. Now the old reference is no longer valid because the Anchor tag was re-created as a new object instance.

What is the difference between getElementById and simply using an element's ID as a variable?

Can someone tell me the difference between calling an HTML elment with id="myDomObect"?:
var myObj = document.getElementById('myDomObect');
&
var myObj = myDomObect;
Use the first form or a wrapper such as jQuery. The second form,
var myObj = myDomObect;
Translates to
var myObj = window["myDomObect"];
This "works" because of an old, old hack in which ID's were exposed as global window properties (IIRC this was a misfeature from the start) and thus we are still blessed with the behavior 20 years later.. and yes, it will work in the very latest Chrome.
However, such a shorthand should not be used for multiple reasons:
It will not work as originally written in "strict mode" (but it will work with the second form)
It does not convey the operation - namely that a DOM element is requested/fetched (by ID).
It does not work for IDs that collide with window properties; eg. <div id=history></div> would result in "unexpected behavior" if accessed this way. (This doesn't affect getElementById code that correctly uses local var variables in a function.)
Behavior is not defined when duplicate IDs exist in the document (which is allowed); the behavior for getElementById has been codified in by DOM 4: "getElementById(elementId) method must return the first element [with the ID], in tree order.."
See also:
Do DOM tree elements with ids become global variables?
The first is how the "real" DOM API works (another option is document.querySelector("#myDomObject")). The second is how browsers have started implementing automatic hoisting of id'd elements, since ids are supposed to be unique. In a twist of "what were you thinking", this can lead to hilarious conflicts where variables that have the same name as HTML elements with an id don't take precedence and the variable you though you were using is suddenly an HTML element.

Javascript: Do properties of `document` include nodes beyond `body`?

I'm reading through Mozilla's Introduction to DOM, and found one of their examples interesting - where body appeared as a property of document. This was atypical to me because I had only seen examples of nodes being accessed using get.
I tried three different ways of accessing the body element of document,
document.body.appendChild(_someNode_)
document['body'].appendChild(_someNode_)
document.getElementsByTagName('body')[0].appendChild(_someNode_)
and found the example shown in Mozilla to be a nice shorthand (first line).
At this point, I felt that I could simply chain nodes with this shorthand, but found that it was undefined for anything but body.
Here's an example:
console.log(document.body); // #document
console.log(document.body.p); // undefined
console.log(document.body.getElementsByTagName('p')[0]); // <p></p>
What's going on here?
There are some tags that get their own properties in document, but they are rare, and in some cases are browser-dependent. An example would be document.forms that contains the collection of all form tags, and document.frames, that contains a collection of al frames and iframes contained by a page.
But you should avoid these properties, and use instead .getElementById(), .getElementsByTagName(), and the more recent and versatile .querySelector() and .querySelectorAll()
The Document object is special. It has a property called body that returns the <body> element, but in general you have to use getElementsByTagName() and its friends.

Element reference breaks on modification of innerHTML property of container

When creating elements via code, I have encountered an issue where modifying the innerHTML property of an element breaks any references to other elements that are injected into the modified element prior to the modification.
I have a test case here: http://jsfiddle.net/mJ7bF/1/ in which I would expect the link1 reference to behave exactly as link2 does.
This second test case is the same code, but instead of using the innerHTML property to add the <br> tag, I create the line break with an object. This test behaves as expected: http://jsfiddle.net/K4c9a/2/
My question is not regarding this specific code, but the concept behind it: what happens to the link1 reference in that first test case? If it doesn't refer to the HTML/DOM node that is visible when the cont node is injected into the document, what DOES it refer to, and how does this fit in with the ByReference nature of javascript objects?
few things here.
first of all. strings are immutable hence doing element.innerHTML += "<br>" acts as a complete read and rewrite.
second, why that is bad:
aside from performance, mootools (and jquery, for that matter) assigns special unique sequential uids to all referenced elements. you reference an element by calling a selector on it or creating it etc.
then consider that SPECIFIC element with uid say 5. the uid is linked to a special object called Storage that sits behind a closure (so its private). it has the uid as key.
element storage then works on a element.store("key", value") and element.retrieve("key")
and finally, why that matters: events are stored into element storage (eg, Storage[5]['events']) - do element.retrieve("events") and explore that in fireBug if you're curious.
when you rewrite the innerHTML the old element stops existing. it is then recreated but the event handler AND the reference to the function that you bound earlier will no longer work as it will now get a NEW uid.
that's about it, hope it makes sense.
to add a br just do new Element("br").inject(element) instead or create a templated fragment for the lot (fastest) and add in 1 big chunk, adding events after.
HTML is represented internally by a DOM object structure. Kind of like a Tree class in traditional programming languages. If you set innerHTML, the previous nodes in the parent node are destroyed, the new innerHTML is parsed, and new objects are created. The references are no longer the same.
div
|-- a..
The div object above contains an Anchor object as a child. Now set a variable link1 as a reference to the address of this Anchor object. Then the .innerHTML is += "<br />", which means all of the nodes of div are removed, and recreated dynamically based on the parsed result of the new value of .innerHTML. Now the old reference is no longer valid because the Anchor tag was re-created as a new object instance.

document.getElementById vs jQuery $()

Is this:
var contents = document.getElementById('contents');
The same as this:
var contents = $('#contents');
Given that jQuery is loaded?
Not exactly!!
document.getElementById('contents'); //returns a HTML DOM Object
var contents = $('#contents'); //returns a jQuery Object
In jQuery, to get the same result as document.getElementById, you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).
var contents = $('#contents')[0]; //returns a HTML DOM Object
No.
Calling document.getElementById('id') will return a raw DOM object.
Calling $('#id') will return a jQuery object that wraps the DOM object and provides jQuery methods.
Thus, you can only call jQuery methods like css() or animate() on the $() call.
You can also write $(document.getElementById('id')), which will return a jQuery object and is equivalent to $('#id').
You can get the underlying DOM object from a jQuery object by writing $('#id')[0].
Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.
The equivalent would be this
var contents = $('#contents').get(0);
or this
var contents = $('#contents')[0];
These will pull the element out of the jQuery object.
A note on the difference in speed. Attach the following snipet to an onclick call:
function myfunc()
{
var timer = new Date();
for(var i = 0; i < 10000; i++)
{
//document.getElementById('myID');
$('#myID')[0];
}
console.log('timer: ' + (new Date() - timer));
}
Alternate commenting one out and then comment the other out. In my tests,
document.getElementbyId averaged about 35ms (fluctuating from 25ms up to 52ms on about 15 runs)
On the other hand, the
jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs).
From this simple test you can see that the jQuery took about 6 times as long.
Of course, that is over 10000 iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate and .fadeTo. But yes, technically getElementById is quite a bit faster.
No. The first returns a DOM element, or null, whereas the second always returns a jQuery object. The jQuery object will be empty if no element with the id of contents was matched.
The DOM element returned by document.getElementById('contents') allows you to do things such as change the .innerHTML (or .value) etc, however you'll need to use jQuery methods on the jQuery Object.
var contents = $('#contents').get(0);
Is more equivilent, however if no element with the id of contents is matched, document.getElementById('contents') will return null, but $('#contents').get(0) will return undefined.
One benefit on using the jQuery object is that you won't get any errors if no elements were returned, as an object is always returned. However you will get errors if you try to perform operations on the null returned by document.getElementById
No, actually the same result would be:
$('#contents')[0]
jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.
Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection
When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object
In case someone else hits this... Here's another difference:
If the id contains characters that are not supported by the HTML standard (see SO question here) then jQuery may not find it even if getElementById does.
This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome:
var contents = document.getElementById('a/b/c');
was able to find my element but:
var contents = $('#a/b/c');
did not.
Btw, the simple fix was to move that id to the name field. JQuery had no trouble finding the element using:
var contents = $('.myclass[name='a/b/c']);
var contents = document.getElementById('contents');
var contents = $('#contents');
The code snippets are not the same. first one returns a Element object (source).
The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery uses document.getElementById() for efficiency.
In both the cases if more than one element found only the first element will be returned.
When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes (https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards)
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.
One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc.
Further, getElementId is called from the document, while $('#...') can be called from a selector. So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form.
<body id="content">
<h1>Header!</h1>
<form>
<div id="content"> My Form </div>
</form>
</body>
It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. The selectivity of jQuery could help you out there.
All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it
<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>
Online Demo!
- https://codepen.io/frank-dspeed/pen/mdywbre
jQuery is built over JavaScript. This means that it's just javascript anyway.
document.getElementById()
The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page.
Jquery $()
Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.
All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :
I have an HTML :
<div id="contents"></div>
Go to console (cntrl+shift+c) and use these commands to see your result clearly
document.getElementById('contents')
>>> div#contents
$('#contents')
>>> [div#contents,
context: document,
selector: "#contents",
jquery: "1.10.1",
constructor: function,
init: function …]
As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:
$('#contents')[0]
>>> div#contents

Categories