It is common for me to register javascript functions for certain events by doing something like:
myBtn.Attributes.Add("onClick", "Validate(getElementById('"+txtFirstName.ClientID + "'));");
I've always used getElementById by itself, or in other words, sans document being prepended to it. But I'm having pages break on me lately when I try to use getElementById instead of document.getElementById. Why is this? Oddly, I have a website where one page allows me to use just getElementById, but another other page throws a javascript error because it can't find the element if I do just getElementById, and it'll only work if I do document.getElementById.
Anyone know why this is? Should I be using document.getElementById everywhere, regardless of whether it works without the document prefix?
EDIT:
Could it have anything to do with the fact that one page is using AJAX and the other isn't?
When you use getElementById() and it works that mean that the function where it's called is running on the context of the document, that's is this == document.
So, you should ALWAYS use document.getElementById to avoid that kind of errors.
Anyway, I would even stop using getElementById altogether and start using JQuery, i'm sure you'll never regret it.
Your code would look something like this if you used JQuery:
$("#myBtnID").click(function () { Validate($("#myTextboxID"))});
Any function or variable you access without an owning object (ex: document.getElementById) will access the property from window.
So getElementById is actually window.getElementById, which isn't natively defined (unless you defined it before (ex: getElementById = document.getElementById).
You should use the full document.getElementById(). If you find that too verbose, you could use jQuery:
$('#' + id)
or you could create an alias at the top of your script:
var byID = document.getElementById;
You should only use document.getElementById (even if I'd recommend using libraries like prototype or jquery to be able to use the $ sign).
If you are able to use getElementById on its own, it's just because the browser you're using is doing some kind of trick to get it to work, but the correct way is to use the document variable.
I dont really know how to explain it but its because the getElementById() finds an element in the html structure of a page. Some browsers know that by default you want to search the document, but other browsers need that extra guidance hence document.
The correct way is indeed document.getElementById().
The reason (speculation) it might work by itself is that depending on where you use it the current context may in fact be the document object, thus inexplicitly resulting in document.getElementById().
Related
I was looking at this question: The preferred way of creating a new element with jQuery
In it, they mention these two methods of using jquery:
Either:
var div = $("<div></div>");
$("#box").append(div);
Or:
$("#box").append("<div></div>");
I'm looking at this, and noticing that if you put actual HTML in the $ function, it acts like you are creating elements in memory. But if you use an HTML selector, it's referring to elements on the document? At least that's my interpretation. I'd like to find all the ways i can use the $ function, but when I search the site, I don't know how to find it.
Can someone list all the ways I can use $, and if possible, links to the official documentation?
$() is a shortcut for the jQuery() function, and you can find the documentation for it here: https://api.jquery.com/jQuery/
Multiple argument types are accepted, including selector, element, elementArray, object, and callback types. From the docs:
In chrome console, i am able to inject a js like below
$("#pageForm").window('open');
And then the DIV form will pop up, however, if i change it to below
document.querySelector("div#pageForm").window('open');
It will return error: Uncaught TypeError: document.querySelector(...).window is not a function
at :1:41
Am I doing wrong in locating an element ?
Thanks
The window method you're calling - whatever that is - is a method that is provided to jQuery by a plugin you're using. It doesn't seem as though jQuery has a window method out of the box. Because you're using a jQuery plugin you need to locate your element using jQuery instead of a query selector.
that $ (dollar sign) you use is jQuery. (It may not be exactly every-day jQuery, it might be something chrome made up for pages that have not jQuery)
there is a difference between the result of $('<some_selector>') & document.querySelector('<some_selector>'); the first one returns a javascript object, which is a wrapper around the DOM Node found in the HTML. this wrapper object has some methods on it (including height(), width(), show(), window(), etc...) which may be added by jQuery or it's plugins (as suggested by Dwight). But the second way (document.querySelector) returns a DOMNode. it is a regular DOM Node and no! it has not a window() method on it
Yes, I agree with answer above. It seems you correctly select the element. However, window property does not belong js out of the box. Its gotta be a jquery plugin so that you can use with jquery. Another function made available to jquery.
You could simply wrap the queryselctor with $
$(document.querySelector("div#pageForm")).window('open');
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 :)
I've looked at some js/jquery code and I saw this line here:
$(this).
How can one find out what methods to call on this thing. Is there something similar to javadocs for js?
Is this code in js or is it jquery?
Note: this might be of relevance to those who reply, I write backend code and never done front end (not more than simple html)
The $ method is just an alias for the jQuery method. It will wrap the element (or object) and expose the methods available to the framework. Many other javascript libraries use $ as an alias as well.
In that case this refers to a DOM element, and $(this) refers to that element turned into a jQuery set.
It then has all the usual jQuery functions
This is jQuery
$(this) is used to when you want to operate on the selected selector
e.g.
If you want to get the value of the text box element with class "email" and this is how the code can be written
$('email').blur(function(){
var email = $(this).val();
});
Because of the limited info you provided, this could be anything. I would put a debug point on $(this). and create a watch on this to see what it is and what methods it exposes. Firebug is really good at showing this.
Following up on my question about jQuery.get() I was wondering if there is a list of DOM properties and methods that aren't available in jQuery that can only be accessible if you were working with the raw DOM object (i.e. $("#someID").get().scrollHeight; )
I haven't encountered a list but if one existed it would probably be quite lengthy. In addition to browser-specific (proprietary) properties there's a bunch of other less useful properties and methods not currently abstracted by jQuery. But then, I don't really see this as a problem, or even a valid point of discussion because jQuery IS JavaScript; if you need access to something beyond what jQuery provides then you can use get() or access a specified element within one of your "jQuery collections" like an array:
jQuery(elem)[0].someDOMProperty;
Plus jQuery provides absolutely no support for non-element nodes within the DOM. If, for whatever reason, you need direct access to comment nodes, text nodes etc. then you'll need to use the "raw" DOM.
I don't know of a compiled list of DOM operations/properties that are NOT available in jQuery (and a quick google search didn't turn anything up), but if you go to http://api.jquery.com/ you can see the entire API, and even download it as an Adobe AIR app in case you don't have internet when you need it.
No. JQuery is just JavaScript. If you can do it in JavaScript, you can do it in jQuery. Some properties and methods are overwritten in the context of a jQuery object and that's where you would want to us the get() method--to 'get' (i.e. access) the standard property/method.
That's really as complicated as it is.
Every attribute of every element is accessible through the attr() function. If you could do a document.getElementById() on that element and then access a property, you can also do it using the attr() function. However, some properties are accessed more easily in other ways when using jquery. For example, to see if an element is hidden or visible, you could do:
var isVisible=$("#el").is(":visible");
instead of using the attr() method. Similarly, you can find the selectedIndex of dropdowns and the text of the selected option, in easier ways than using the attr() method. This pdf outlines some of these easier approaches.
To access a css property, you are better off doing:
var fontWeight=$("#el").css("fontWeight");
rather than using get() or attr(). You can also set the css properties in this way, e.g:
$("#el").css("fontWeight","bold");
I could be wrong, but I think you can access any properties via the attr method.