Selecting a DOM element using javascript document.myElementsName - javascript

I'm working on a website which was coded a while ago.
I've found a Javascript function that uses the following syntax to set a value for a text box
document.myForm.myText.value = "value";
I've tested this code and it works in IE, Firefox and Chrome.
My question is whether this way of setting/selecting DOM elements is ok going forward (ie. is it going to get depreciated)? Should I change instances of this type of element selecting to the more standard (in my experience) code below?
document.getElementById("myText").value = "value";
Thanks in advance.

I don't think it'll make a difference cause the browsers dom representation will have change to break the code; That'll probably break half the web pages on the internet.
Your code is better than the first because you will then be coding to the contract of the method getElementById, which returns the HTMLElement you need. This means that the JS Engine has to adhere to the standards of ECMAScript and return the exact element. Hence your code doesn't need to worry if tomorrow a browser changes it's structure and your element is now document.forms.myForm.myText.value instead of what you anticipated.

Related

in chrome just typing id of element automatically selects it

So if i have element with id asd. And i go write asd in console it will get selected. And if i write asd.addEvent...etc in script file it will work. I didn't use getElementById(.. or anything. I am confused since when did it start happening. And is it only chrome specific thing. Or Firefox and other browsers have it too. Then Why even type documentGetElementById()... I tried incognito mode and it worked there too. So it's not some plugins messing up.
Summary: I type id and element is selected.
As pointed out this appears to be a duplicate of Do DOM tree elements with ids become global variables?
Stick to document.getElementById, which is more widely-supported and less ambiguous. You can write a trivial wrapper function with a shorter name if you don't like the typing.
The short and simple answer is that compatibility is king: When you publish code for the public web with its hundreds of browser variants, taking shortcuts which potentially exclude some of your audience is a bad idea.

addEventListener() without getElementById reference success?

Check out this fiddle (partial code snippet below): http://jsfiddle.net/QJJb8/
<button id='mybutton'>MY BUTTON</button>
mybutton.addEventListener('click', mybuttonClick, false);
function mybuttonClick(e){
alert(e.target.textContent+' WAS CLICKED!');
}
Note how I'm not using getElementById() to get a reference to the button. Why does it still work? (Tested in Firefox, Chrome and IE9 & 10.)
Is it bad-practice/quirk, or is it built in functionality for button elements? If the latter, that's an awesome perk/shortcut when using button elements! Or perhaps I've just been over-using getElementById() all this time?
//ANSWER UPDATE//////////////////////////////////////////////////////////////////////
After some research it seems the behavior discussed above is in fact part of the HTML5 spec. In addition to RobG's answer below, see also the following links for more insight:
http://tjvantoll.com/2012/07/19/dom-element-references-as-global-variables/
https://stackoverflow.com/a/3434388/2434324 (link supplied by yoelp)
http://jsperf.com/named-access-on-the-window-object
Because way back at the begining of browser scripting, IE decided to make element names and IDs global variables that referenced the element. Everyone else thought that was a bad idea (it was) and didn't do it.
However, IE grabbed about 95% of the browser market and developers developed for IE's quirks, so other browsers implemented the same behaviour but didn't advertise it (same with support for document.all). So now all browsers do it, but (almost) no one uses it.
Except when someone stumbles across it…
So where you have:
<button id='mybutton' ...>
browsers create a global mybutton variable that references the element.
This works on all DOM elements, not only buttons, Its probably a bad practice since any one may change mybutton to something else (ie.mybutton = "BLABLA") then your code breaks
also see this

Create a <noscript> element with content fails on IE7 and IE8 (jQuery)

I've seen several threads about reading contents, but nothing on writing to noscript.
$('body').append('<noscript><div></div></noscript>');
In Chrome and IE9 I get a noscript-element with a empty div inside like I expect, but in IE7 and IE8 I just get a empty noscript-element without the div inside.
Example: http://jsfiddle.net/cEMNS/
Is there a way to add HTML inside the noscript-tag that works in all browsers? What I need is to add some tracking code into a noscript-element at the end of the page, but the info I need isn't available until after document ready.
Edit: I'm getting a lot of comments on "why". It's some poorly done tracking library that requires this. We don't have access to the code to change it. Regardless, I find it interesting that it works in some browsers and not in others since jQuery was supposed to work equally in all browsers. Is it simply a bug?
Edit2: (2 years later) Adding a noscript on the browser doesn't make sense, I know. My only excuse not the question the task I had was because of lack of sleep, like everyone else in the project. But my rationale was that jQuery should behave the same on all browsers and someone might want to do this on the server.
Regardless of the tracking code, what you are doing (or are required to do) makes no sense!
Why? There are two cases possible here:
user has JavaScript enabled in which case the NOSCRIPT get's inserted into the DOM but is ignored by the browser (does nothing)
user does not have JavaScript enabled, NOSCRIPT does not get inserted and does not "execute"
The end result of both cases is that nothing actually happens.
Just an idea: You could try giving your noscript tag an ID, and then try to use native js.
for example:
$('body').append('<noscript id="myTestNoScript"></noscript>');
document.getElementById('myTestNoScript').innerHTML = '<div></div>';
I would claim that if it does not work with native js, it will not work with any library (feel free to correct me on this one).
I tried following simple HTML code:
<html>
<body>
<noscript>I'm a noscript tag.</noscript>
</body>
</html>
Then I did analyse this with IE8 (in IE7 mode) and his integrated code insprector. Apparently the IE7 checks are script allowed. If so he declared it as empty. And empty tags will be ignored. Unfortunatly I could not try that with disabled script option, because only the Systemadministrator can change the settings (here at my work).
What I can assure you, the noscript does exists. If you add
alert($('noscript').size());
after the creation, the result will be 1.

AppendChild issue with Internet Explorer Javascript

The following piece of code, works correctly in Firefox and Chrome, but it gives me a headache in IE.
var anotherDiv= document.getElementById("anotherDiv");
var destination = document.getElementById("mySourceDiv");
destination.appendChild(anotherDiv);
I'm trying to get a Div element and place it inside another div.
I get an error message (in the debug console in IE) similar to "interface not supported", and points me to the appendChild line.
What I've seen is that the type of the destination variable is an object rather then a DOM element.
What can I do to append the anotherDiv to mySourceDiv?
I'm trying this in IE 8.
You probably will need something like an importNode, there are various cross browser solutions around. The issue is that each node has a corresponding document object on it, in IE and so called security doesn't play nice moving things from one document to another.
So, essentially it's doing a deep clone, but the difference between using cloneNode is that cloneNode also sets the document which you don't want.
This might get you going in the right direction:
IE support for DOM importNode
I'd recommend using a library designed to sort through the browser incompatibilities for you. I've personally found jQuery to be quite good. jQuery has an append function.

Stupefyingly weird IE 9 Javascript bug: Altering doc title makes subsequent code execute

I don't understand this at all. Here is some Javascript code that works in every browser but IE 9. It is called from a Flash movie using ExternalInterface, and is meant to dynamically resize the movie in the DOM if the size of the movie changes internally
function vResizeFlash(swfId, ht) {
document.getElementById(swfId).height = "100%";
document.getElementById('flashContainer').style.height = ht + "px";
}
But it works fine if I alter the document.title:
function vResizeFlash(swfId, ht) {
// IE 9 won't run the rest of this function unless
// we go through the charade of changing the document title.
if (navigator.appName.indexOf("Microsoft") != -1) {
var docTitle = document.title.replace(/^(.+?)\s*$/,"$1");
document.title = docTitle + " ";
}
// Well-coded browsers begin here
document.getElementById(swfId).height = "100%";
document.getElementById('flashContainer').style.height = ht + "px";
}
Here I simply trim any white-space from the right side of the document.title, then add a single white-space character to it. Suddenly the following lines get executed. Note: there are other ExternalInterface calls on the page, and all of them work fine, even in IE 9, so it's not a Flash/IE 9 problem.
I stumbled on the fix because I was altering the title to show the function arguments (as a quick debugging test), just to make sure the function was getting run. And suddenly the code worked. Take it out? Doesn't work. 100% reproducible.
Anybody know why this absolutely stupefying behavior takes place?
UPDATE
#c69 has posed the question: "Maybe its IE9's dead code remover?"
I didn't know about this, so I went and Googled and found this article on the topic, as well as some discussion of it elsewhere. I don't know enough about it to evaluate how this would affect a two-line Javascript function, however, especially since one of the lines does have a referent on the page (although it is late-loading through the SwfObject code). Still, it would be a pretty bad bug for a code "optimizer" to remove lines of code it deemed unnecessary because it doesn't understand how they are called. And if it did fail to understand how the lines are called, how does inserting a line making a bogus change to the document.title render that code suddenly "necessary"?
UPDATE 2
Another piece of the puzzle This may have something to do with IE 9's compatibility mode. The page starts out in IE 9's standards mode.
Now, if I turn on IE's compatibility mode,
the problem goes away without using the above hack. Turn it off, and the problem returns (if no hack present).
But when I tried to make a simple test using the exact same HTML (minus a couple of JSP tags) and a stripped down SWF that only contains the resize code and the tools to test, everything works fine. In that case, however, no compatibility icon is displayed at all.
We're using Tomcat 6.0.32. I'm not aware that we are using any special headers, and there are no meta tags regarding IE compatibility mode (in either the main app or in my test app).
like InvertedSpear mentions, check your doc type out, i've had problems with IE9 recently and most of it boiled down to the Doc type tags triggering a compatability mode i didn't need, the same can be true of the meta tags so it might boil down to your Meta tags.
You can always impose a working compatibility mode using the links below too.
from: http://evolpin.wordpress.com/2011/02/25/ie9-compatibility-and-the-meta-tag/
I’ve discovered that this is indeed documented by Microsoft…
http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
“The X-UA-Compatible header is not case sensitive; however, it must appear in the header of the webpage (the HEAD section) before all other elements except for the title element and other meta elements.”
Whenever I see something like this happen in any language it's because there is other code that has a bug. As you pointed out your simple case doesn't produce the problem. Try removing other code a few lines at a time until the problem disappears - the last removed code should contain the problem.
Cheers

Categories

Resources