do I really need to call getElementById()? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
I just stumbled upon an unexpected but useful behavior in the browser: It creates a variable for every element that has an ID in my html code. So when I have:
<div id="ohlala"> ... </div>
the browser seem to run this code behind the scene:
var ohlala = document.getElementById("ohlala");
so I can easily change the text of that element by:
ohlala.innerHTML="test"
Try it online: http://jsfiddle.net/Facby/
The question is: why would I need to write the document.getElementById() bit myself? How portable is that code? I tried in Opera, FireFox and Chrome and it works! Can I rely on this functionality? Does the browser always create variables for every element with id? In that case I have to be more careful about the names that are used in my javascript code not to conflict with similar ids from the HTML, right?

When creating elements with IDs, the "window" object receives the specific attributes, that's why you can use variables directly, this behavior is deprecated and usually is wrote like this: window.ohlala.innerHTML = "...", this behavior is conserved by the browsers for compatibility with some older code on websites, but it is not recommended to use it in modern websites, always use .getElementById() method, this method is part of a W3C Standard, and you can use it in all modern browsers, in some very old browser versions and < IE7 it will not work. Learn more about DOM (Document Object Model) here: https://developer.mozilla.org/en-US/docs/DOM

Related

Access HTML elements based on id identifier [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 9 years ago.
I was playing with javascript, and I don't understand how this little snippet can works:
html > <div id="foo_bar"></div>
javascript > foo_bar.textContent = "Hello, world!";
result > <div id="foo_bar">Hello, world!</div>
foo_bar is not a variable defined before in the code. I only have this one line in my javascript code.
Check the jsFiddle demo : http://jsfiddle.net/6W25e/
So what really happend?
I always thought that was impossible to access dom elements without dom methods like element.getElementById().
Is there any documentation on this behavior? (my searches have been unsuccessful on mdn)
Taken from bobInce
What is supposed to happen is that ‘named elements’ are added as apparent properties of the document object. This is a really bad idea, as it allows element names to clash with real properties of document.
IE made the situation worse by also adding named elements as properties of the window object. This is doubly bad in that now you have to avoid naming your elements after any member of either the document or the window object you (or any other library code in your project) might want to use.
Read more: Do DOM tree elements with ids become global variables?
This means it's very bad practice to do that, and some browsers don't support it, the good ones that don't fall into the trick.
What happens is that some browsers will make them global variables as classes of window, making them immediately accessible when the window loads.

Crossbrowser alternative for html = $('html')

Is it too lame to write like this?
var html = $('html');
Seems that html is equal to $(window) or $(document)?
How can it be replaced by a crossbrowser native javascript?
The top-level element (html in the case of HTML documents) is available as document.documentElement (references: spec | MDN).
And of course, if you want to use jQuery stuff on it, get a jQuery wrapper: $(document.documentElement).
In terms of cross-browser support, I'd be fairly shocked if you found anything even vaguely recent that didn't support it (and that includes IE6), it was actually in DOM1, which was a long time ago. See this related question on that very topic.

DOM manipulation - Why removeChild() method instead of remove()? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does removeChild need a parent node?
Cross-browsers way to remove a node element is to use removeChild() method.
However, this way expects us to precise the node's parent as follows:
myNodeToRemove.parentNode.removeChild(myNodeToRemove);
Why didn't browsers implement the remove method with a more object-oriented way like this:
myNodeToRemove.remove();
With remove() method starting as follows:
function remove(){
var parentNode = this.parentNode;
....
}
Indeed, using this way, no need to manually get the node's parent.
For the question:
Why didn't browsers implement the remove method with a more object-oriented way like this
myNodeToRemove.remove();
...you need to study Javascript history, how the language was born, how APIs were born and so on. Then you understand how we ended up with the clusterfuck called modern web. The history is hilarious.
Good place to start is to watch Crockford on Javascript videos
http://javascript.crockford.com/#video
Also regarding function naming and object-oriented practices this is a good video:
http://vimeo.com/43380467
I think the reason to use the combination of parentNode and removeChild ensures that we are referencing the removeChild method on the actual parent of the container that we wish to remove.

Is getElementById optional in some browsers? [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 8 years ago.
When accessing elements by window.someThing, the "someThing" should be the name of html element. But what I see now, is that I can access an element by id in the same way, without document.getElementById. When has this been changed? It looks like it works in Chrome, IE, Firefox 13, but not in Firefox 12.
For example:
<div id="MyDiv">Content</div>
<script>
MyDiv.innerHTML = "New Content";
</script>
Why does the example above work? Why don't I have to do:
var MyDiv = document.getElementById('MyDiv');
Is it something new, or has it always been possible and I just didn't know it?
http://www.quirksmode.org/dom/w3c_core.html#gettingelements
It's been (mostly) implemented since IE 5.5
I can't really find any info on using the ID as variable name. I'd suggest on sticking to getElementById("MyDiv").doSomething instead of MyDiv.doSomething, to improve compatibility.
Especially when you're writing larger scripts, you may mix up variable names with id's used in the page. getElementById ensures you "get" the DOM element.
This is not standard behavior in JavaScript. When adding a variable as you did with var MyDiv, the variable was added to the window object so that it could be accessed directly as if it were a property, but DOM elements were never added. I don't personally know the reasons for the new behavior, but my guess would be that it's just an expansion of the language engine's capability. If you really want to know what the behavior is supposed to be, you could always read the standard: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Edit: Also, note that the method that is used to get the element is document.getElementById() which comes from the document object model. The method you're referring to is placing an id into the window object which can create conflicts by id. The standard defined method is to get the element from document and avoid putting things into the window. Using the window object in this manner would be similar to using a global variable (which is a bad practice re: http://www.javascripttoolbox.com/bestpractices/#namespace)
You can find your answer here: Can I Use an ID as a Variable Name?
In short, avoid it.
The reason it works is because the browser actually creates a variable window.document.myDiv
AVOID IT!
It seems like an amazing feature but I would recommend not using it because if you have divs with id same as that of some global JS variables, it would be conflicting and will also mess-up stuff in some other third party JS files that you include.
But You always have jQuery selectors always with you and not to forget the new querySelector feature in modern browsers :)

What are the typical reasons Javascript developed on IE fails on Firefox?

I often suffer from the problem opposite what's described in this post. That is, I've got code in a legacy application designed only for Internet Explorer and I need to get it to work in Firefox.
For example, I recently worked on an app that made heavy use of manually simulating click events, like this:
select.options[0].click();
...which completely broke the application in Firefox. But you wouldn't find that information in the answers to the other question, because that's not something you'd ever even attempt if your app first targeted Firefox.
What other things should a developer updating a legacy IE-only application look for when migrating to modern browsers?
Here's what my previous research uncovered. I've seen each of these issues prevent a real-world application from working in Firefox. Please feel free to edit.
The DOM
document.createElement should take only a tag name, but IE lets you
pass arbitrary HTML (with attributes, etc)
http://msdn.microsoft.com/en-us/library/ms536389(VS.85).aspx
document.getElementById should only find elements with the given id,
but IE also returns elements with the given name
http://msdn.microsoft.com/en-us/library/ms536437(VS.85).aspx
IE creates implicit global variables for DOM elements, but referencing an element this way in Firefox produces the following warning:
"Element referenced by ID/NAME in the
global scope. Use W3C standard
document.getElementById() instead."
http://www.west-wind.com/weblog/posts/677442.aspx
http://code.google.com/p/fbug/issues/detail?id=853
IE's document.all is a collection of all elements in the document. It is not supported by Firefox.
http://msdn.microsoft.com/en-us/library/ms537434(v=vs.85).aspx
An Element's text in IE is retrieved using the innerText property. Firefox calls this property textContent.
http://msdn.microsoft.com/en-us/library/ms533899(v=vs.85).aspx
IE allows items in collections to be referenced using function syntax (i.e. with parentheses) instead of the normal array indexing syntax (i.e. with brackets). For example, the following works in IE: document.forms(0). Firefox does not support this usage.
http://msdn.microsoft.com/en-us/library/ms537457(v=VS.85).aspx
HTMLTableElement rows and cells should refer to HTMLCollections, but
IE allows them to be called as functions; Firefox does not.
http://msdn.microsoft.com/en-us/library/ms537484%28VS.85%29.aspx
IE defaults insertRow's index to -1; Firefox errors if the argument is omitted.
http://msdn.microsoft.com/en-us/library/ms536457%28VS.85%29.aspx
https://developer.mozilla.org/en/DOM/table.insertRow
The Node.text property is IE-only
http://msdn.microsoft.com/en-us/library/ms534677%28VS.85%29.aspx
https://developer.mozilla.org/En/DOM/Node.textContent
Events
window.event is an IE-specific way to access event information; it's not
supported by Firefox.
http://msdn.microsoft.com/en-us/library/ms535863(v=vs.85).aspx
http://www.quirksmode.org/js/events_access.html#link3
Events are attached to Elements in IE using attachEvent. Firefox uses addEventListener. Note, also, that the names of events are subtly different in each browser.
http://msdn.microsoft.com/en-us/library/ms536343(v=vs.85).aspx
In IE it's possible to get the mouse position from non-mouse events, but it's not in other browsers. In addition, the names of the mouse-coordinate properties are not the same in IE and Firefox.
http://msdn.microsoft.com/en-us/library/ms533567(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms533568(v=vs.85).aspx
http://www.quirksmode.org/js/events_properties.html#position
IE supports a click method for triggering the onclick event on HTML elements. No such function exists in Firefox.
http://msdn.microsoft.com/en-us/library/ms536363(v=vs.85).aspx
http://lifescaler.com/2008/04/simulating-mouse-clicks-in-javascript/
http://www.devtoolshed.com/content/fix-firefox-click-event-issue
XML
Firefox splits text nodes into 4096-char blocks; IE does not. This
means that things like childNodes will be different in IE and Firefox.
Is there a 4096 character limit for JavaScript XML text nodes?
Internet Explorer defines a parseError.errorCode property on
XMLDocuments for detecting parser errors. Firefox loads an XML document that contains error information in the document with documentElement.nodeName=="parsererror".
IE ignores whitespace in XML; firstChild always returns the first
ELEMENT_NODE
http://www.w3schools.com/dom/prop_element_firstchild.asp
https://developer.mozilla.org/en/Whitespace_in_the_DOM
The Node.xml property is IE-only
http://www.w3schools.com/dom/prop_node_xml.asp
http://www.grange.com.br/dicas-tecnicas/40-lotus/345-dom-xml-wrapper-for-javascript
Further reading
http://www.reloco.com.ar/mozilla/compat.html
https://developer.mozilla.org/en/migrate_apps_from_internet_explorer_to_mozilla
http://www.impressivewebs.com/7-javascript-differences-between-firefox-ie/
You should note that Microsoft has a problem with making their own version of everything, and naming it after themselves.

Categories