I have:
<div id="myDiv1"></div>
<div id="myDiv2"></div>
In JavaScript, I can set div innerHTML by writing:
myDiv1.innerHTML = "myDiv1, Hi!"
or
document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!"
Why should I use document.getElementById when I can simply use element Id ? Is this working every time or only in some special scenarios (like simple sample)?
thanks,
Mike
Why should I use document.getElementById when I can simply use element Id ?
To avoid conflicts. The global namespace on browsers is incredibly crowded, all sorts of things are dumped in there, including (as you've found) globals referring to any element with an id (so-called "automatic globals").
In contrast, getElementById only does what it says, finds an element by its id; it's more constrained. (Other than bugs in old versions of IE, which also looked at elements with name attributes.)
when you write
myDiv1.innerHTML = "myDiv1, Hi!"
you are calling window object, so actual call is like this
window.myDiv1.innerHTML = "myDiv1, Hi!"
This behavior is deprecated now and to be avoided. Instead we should use
document.getElementById`
Related
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.
Dear StackOverflow community,
I am new to jQuery and Javascript, and was wondering what the main differences between these two functions are:
document.getElementById('id').innerHTML =variable;
and
jQuery('#id').val(variable);
From my understanding, they are two different coding techniques, but when would I use one over the other? and why?
The two above examples are slightly different, but not in the way you're expecting.
innerHTML and .val() are not equivalent methods.
jQuery will try to use querySelector / querySelectorAll where appropriate when using the DOM selection jQuery("SELECTOR"). These are native methods, so look into them.
.val(variable) will set the value of the node found by jQuery("SELECTOR") to variable
innerHTML = variable will set the the HTML content of document.getElementById('id') to whatever variable is.
.val() - Set the value of each element in the set of matched elements.
innerHTML - innerHTML sets or gets the HTML syntax describing the element's descendants.
I recently found on this javascript tip :
element_number = Array.prototype.indexOf.call(element_1, element_2);
It allows developers to use the indexOf method on an object wich is not an Array.
I would like to know if it is possible to use a similar syntax to call the getElementById method but not on the whole document (document.getElementById), just on an element like this :
my_div_2 = document.prototype.getElementById.call(div_1, "id_of_my_div_2");
The idea is that my document contains tabs and elements having the same id can be present several times in the document.
If it is not possible, did somebody write a function doing that :
Search in an element another element by id.
No, but you can accomplish what you want using querySelector instead.
my_div_2 = div_1.querySelector("#id_of_my_div_2");
Not supported in IE6/7.
Docs: MDN element.querySelector()
That said, duplicate IDs are invalid.
This technique is useful if the same script is used on different pages where the ID may or may not be in a particular container.
No. The getElementById method must be applied on objects of type Document, otherwise it would throw a WRONG_THIS_VALUE exception. You could try it with
myDiv1 = document.getElementById("div1");
myDiv2 = document.getElementById.call(myDiv1, "div2"); // no ".prototype"!
This makes no sense as only one element with a given id is possible in a document.
So the only right syntax would be
my_div_2 = document.getElementById("id_of_my_div_2");
Don't reuse an id in a document. You probably can achieve the desired result using classes instead of id.
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
I've got a simple select input and I'm using jQuery's .val() to get the selection from it.
For some reason, it is throwing a "Object doesn't support this property or method" error in Internet Explorer 8, the first error I've ever seen jQuery actaully throw.
I've replicated this error at http://jsfiddle.net/gWvwS
What am I doing wrong? Seems pretty straight forward to me...
Try:
var isplay_entry_form = $('#display_entry_form').val();
alert(isplay_entry_form);
display_entry_form on the global window is actually the element. It's much less known, because it's really bad and shouldn't be used. So you are overwriting it in IE.
Fixed Example for IE8: http://jsfiddle.net/gWvwS/7/
Javascript variables with the same name as DOM elements are not supported by IE. It appears that IE uses a common mechanism for addressing DOM elements by id and addressing javascript variables. Which means that whichever object (DOM element or javascript var) is declared later in the source is the one that gets used. This will likely cause an "object does not support this property or method" error when you try to access your javascript variable. (source)
This should work:
display_entry_form_value = $('#display_entry_form > option:selected').val();
alert(display_entry_form_value);
Your document contains an element with name display_entry_form. In IE, named elements are globally accessible through their name. So, you have to either use var (to declare a new, local variable[Need verification]), or choose another name.
var other_name = $('#display_entry_form').val();
alert(other_name);
Fiddle http://jsfiddle.net/gWvwS/5/
I suppose it has to do with, that value belongs to option, not to select.
Try
$('select#display_entry_form option:selected').val();
I updated jsfiddle to correct code:
http://jsfiddle.net/gWvwS/6/
The <select> tag doesn't have a value attribute, but rather a selectedIndex attribute.